package com.ruoyi.project.mobile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.uniquekey.IdGererateFactory;
import com.ruoyi.common.utils.wxmessage.SendWxMessage;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.jiaqin.advertcontract.domain.JiaqinAdvertContract;
import com.ruoyi.project.jiaqin.advertcontract.service.IJiaqinAdvertContractService;
import com.ruoyi.project.jiaqin.advertcooperate.domain.JiaqinAdvertCooperate;
import com.ruoyi.project.jiaqin.advertcooperate.service.IJiaqinAdvertCooperateService;
import com.ruoyi.project.jiaqin.advertplatform.domain.JiaqinAdvertPlatform;
import com.ruoyi.project.jiaqin.advertplatform.service.IJiaqinAdvertPlatformService;
import com.ruoyi.project.jiaqin.answerreply.domain.JiaqinAnswerReply;
import com.ruoyi.project.jiaqin.answerreply.service.IJiaqinAnswerReplyService;
import com.ruoyi.project.jiaqin.apply.domain.CompanyApply;
import com.ruoyi.project.jiaqin.apply.service.ICompanyApplyService;
import com.ruoyi.project.jiaqin.company.domain.Company;
import com.ruoyi.project.jiaqin.company.service.ICompanyService;
import com.ruoyi.project.jiaqin.companyautograph.domain.CompanyAutograph;
import com.ruoyi.project.jiaqin.companyautograph.service.ICompanyAutographService;
import com.ruoyi.project.jiaqin.companycarousel.domain.CompanyCarousel;
import com.ruoyi.project.jiaqin.companycarousel.service.ICompanyCarouselService;
import com.ruoyi.project.jiaqin.companyenvironment.domain.CompanyEnvironment;
import com.ruoyi.project.jiaqin.companyenvironment.service.ICompanyEnvironmentService;
import com.ruoyi.project.jiaqin.companyindustry.domain.CompanyIndustry;
import com.ruoyi.project.jiaqin.companyindustry.service.ICompanyIndustryService;
import com.ruoyi.project.jiaqin.companyinfo.domain.CompanyInfo;
import com.ruoyi.project.jiaqin.companyinfo.service.ICompanyInfoService;
import com.ruoyi.project.jiaqin.companyproduct.domain.CompanyProduct;
import com.ruoyi.project.jiaqin.companyproduct.service.ICompanyProductService;
import com.ruoyi.project.jiaqin.companyrecruit.domain.CompanyRecruit;
import com.ruoyi.project.jiaqin.companyrecruit.service.ICompanyRecruitService;
import com.ruoyi.project.jiaqin.downquotation.domain.DownQuotation;
import com.ruoyi.project.jiaqin.downquotation.service.IDownQuotationService;
import com.ruoyi.project.jiaqin.followcompany.domain.JiaqinFollowCompany;
import com.ruoyi.project.jiaqin.followcompany.service.IJiaqinFollowCompanyService;
import com.ruoyi.project.jiaqin.followmember.domain.JiaqinFollowMember;
import com.ruoyi.project.jiaqin.followmember.service.IJiaqinFollowMemberService;
import com.ruoyi.project.jiaqin.membernewslikes.domain.MemberNewsLikes;
import com.ruoyi.project.jiaqin.membernewslikes.service.IMemberNewsLikesService;
import com.ruoyi.project.jiaqin.news.domain.News;
import com.ruoyi.project.jiaqin.news.service.INewsService;
import com.ruoyi.project.jiaqin.newsclass.domain.NewsClass;
import com.ruoyi.project.jiaqin.newsclass.service.INewsClassService;
import com.ruoyi.project.jiaqin.newscommentlikers.domain.NewsCommentLikers;
import com.ruoyi.project.jiaqin.newscommentlikers.service.INewsCommentLikersService;
import com.ruoyi.project.jiaqin.newsfollow.domain.NewsFollow;
import com.ruoyi.project.jiaqin.newsfollow.service.INewsFollowService;
import com.ruoyi.project.jiaqin.newsimg.domain.NewsImg;
import com.ruoyi.project.jiaqin.newsimg.service.INewsImgService;
import com.ruoyi.project.jiaqin.numbertips.domain.NumberTips;
import com.ruoyi.project.jiaqin.numbertips.service.INumberTipsService;
import com.ruoyi.project.jiaqin.question.domain.JiaqinQuestion;
import com.ruoyi.project.jiaqin.question.service.IJiaqinQuestionService;
import com.ruoyi.project.jiaqin.quotation.domain.Quotation;
import com.ruoyi.project.jiaqin.quotation.service.IQuotationService;
import com.ruoyi.project.jiaqin.quotationclass.service.IQuotationClassService;
import com.ruoyi.project.jiaqin.quotationcollect.domain.QuotationCollect;
import com.ruoyi.project.jiaqin.quotationcollect.service.IQuotationCollectService;
import com.ruoyi.project.jiaqin.quoted.domain.QuotedPrice;
import com.ruoyi.project.jiaqin.quoted.service.IQuotedPriceService;
import com.ruoyi.project.jiaqin.region.domain.Region;
import com.ruoyi.project.jiaqin.region.service.IRegionService;
import com.ruoyi.project.jiaqin.supply.domain.Supply;
import com.ruoyi.project.jiaqin.supply.service.ISupplyService;
import com.ruoyi.project.jiaqin.supplycollect.service.IJiaqinSupplyCollectService;
import com.ruoyi.project.jiaqin.vipconfig.domain.VipConfig;
import com.ruoyi.project.jiaqin.vipconfig.service.IVipConfigService;
import com.ruoyi.project.jiaqin.wanttobuy.domain.WantToBuy;
import com.ruoyi.project.jiaqin.wanttobuy.service.IWantToBuyService;
import com.ruoyi.project.jiaqin.wanttobuycollect.domain.WantToBuyCollect;
import com.ruoyi.project.jiaqin.wanttobuycollect.service.IWantToBuyCollectService;
import com.ruoyi.project.system.bundleapplication.domain.BundleApplication;
import com.ruoyi.project.system.bundleapplication.service.IBundleApplicationService;
import com.ruoyi.project.system.cardstylebackground.domain.CardStyleBackground;
import com.ruoyi.project.system.cardstylebackground.service.ICardStyleBackgroundService;
import com.ruoyi.project.system.cardstyleshow.domain.CardStyleShow;
import com.ruoyi.project.system.cardstyleshow.service.ICardStyleShowService;
import com.ruoyi.project.system.coinrecord.domain.HaoqiCoinRecord;
import com.ruoyi.project.system.coinrecord.dto.HaoqiCoinRecordDto;
import com.ruoyi.project.system.coinrecord.service.IHaoqiCoinRecordService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.enums.MemberIsVip;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.memberbusiness.domain.MemberBusiness;
import com.ruoyi.project.system.memberbusiness.service.IMemberBusinessService;
import com.ruoyi.project.system.memberdepartment.domain.MemberDepartment;
import com.ruoyi.project.system.memberdepartment.service.IMemberDepartmentService;
import com.ruoyi.project.system.memberduties.domain.MemberDuties;
import com.ruoyi.project.system.memberduties.service.IMemberDutiesService;
import com.ruoyi.project.system.membershareslogan.domain.MemberShareSlogan;
import com.ruoyi.project.system.membershareslogan.service.IMemberShareSloganService;
import com.ruoyi.project.system.memberspreadbackground.domain.MemberSpreadBackground;
import com.ruoyi.project.system.memberspreadbackground.service.IMemberSpreadBackgroundService;
import com.ruoyi.project.system.messageinfo.domain.MessageInfo;
import com.ruoyi.project.system.messageinfo.service.IMessageInfoService;
import com.ruoyi.project.system.messageuser.domain.MessageUser;
import com.ruoyi.project.system.messageuser.service.IMessageUserService;
import com.ruoyi.project.system.modularshow.domain.ModularShow;
import com.ruoyi.project.system.modularshow.service.IModularShowService;
import com.ruoyi.project.system.notification.domain.PlatformNotification;
import com.ruoyi.project.system.notification.service.IPlatformNotificationService;
import com.ruoyi.project.system.paylog.domain.PayLog;
import com.ruoyi.project.system.paylog.service.IPayLogService;
import com.ruoyi.project.system.shopconfig.domain.ShopConfig;
import com.ruoyi.project.system.shopconfig.service.IShopConfigService;
import com.ruoyi.project.system.visitor.domain.JiaqinVisitor;
import com.ruoyi.project.system.visitor.service.IJiaqinVisitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 新接口
 *
 * @autor LCL
 * @date - 2021/9/28
 */
@RestController
@RequestMapping("/api/new")
public class ApiNewController extends BaseController {

//    @Autowired
//    private IGoodsTeamService goodsTeamService;
    @Autowired
    private IJiaqinVisitorService jiaqinVisitorService;
    @Autowired
    private ICompanyProductService companyProductService;
    @Autowired
    private ICompanyEnvironmentService companyEnvironmentService;
    @Autowired
    private IQuotationService quotationService;
    @Autowired
    private ISupplyService supplyService;
    @Autowired
    private IWantToBuyService wantToBuyService;
    @Autowired
    private IPlatformNotificationService platformNotificationService;
    @Autowired
    private IHaoqiCoinRecordService coinRecordService;

    /**
     * 添加今日访客
     *
     * @param memberId        用户ID
     * @param visitorMemberId 被访问用户ID
     * @param type            0-访问，1-退出
     * @return R.ok();
     */
    @GetMapping("/visitorsToday")
    public R visitorsToday(String memberId, String visitorMemberId, Integer type) {
        if (memberId == null || memberId.equals("") || visitorMemberId == null || visitorMemberId.equals("")) {
            return R.error("缺少用户ID");
        }
        // 查询今日是否访问
        JiaqinVisitor byMemberIdAndVisitorMemberId = jiaqinVisitorService.findByMemberIdAndVisitorMemberId(memberId, visitorMemberId);

        JiaqinVisitor visitor = new JiaqinVisitor();
        if (!memberId.equals(visitorMemberId)) {
            // 添加今日访客
            if (byMemberIdAndVisitorMemberId == null && type == 0) {
                visitor.setMemberId(memberId);
                visitor.setVisitorMemberId(visitorMemberId);
                visitor.setVisitorAt(new Date());
                visitor.setVisitorType(0);
                visitor.setNum(1);
                visitor.setDelFlag(0);
                jiaqinVisitorService.insertJiaqinVisitor(visitor);
                // 添加今日访客数字提示
                NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(visitorMemberId);
                if (numberTips != null) {
                    NumberTips tips = new NumberTips();
                    tips.setId(numberTips.getId());
                    tips.setVisitorNum(1);
                    numberTipsService.updateNumberTips(tips);
                }
            } else if (byMemberIdAndVisitorMemberId != null) {
                visitor.setId(byMemberIdAndVisitorMemberId.getId());
                visitor.setVisitorAt(new Date());
                // 退出时间
                if (type == 1) {
                    visitor.setVisitorOutAt(new Date());
                }
                visitor.setNum(byMemberIdAndVisitorMemberId.getNum() + 1);
                jiaqinVisitorService.updateJiaqinVisitor(visitor);
            }
        }
        return R.ok();
    }

    /**
     * 根据用户ID查我的今日访客
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getMyVisitors")
    public R getMyVisitors(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                           String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member memberById = memberService.selectMemberById(memberId);
        if (memberById == null) {
            return R.error("请先注册");
        }
        // 不是会员，请先注册会员
        if (memberById.getIsVip() == 0 && memberById.getIsJqVip() == 0) {
            return R.error("您不是会员，请先注册会员");
        }
        // 取消今日访客数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setVisitorNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        PageInfo<JiaqinVisitor> pageInfo = jiaqinVisitorService.getMyVisitors(pageNum, pageSize, memberId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo);
        return R.ok(map);
    }

    /**
     * 提交公司环境
     *
     * @param companyEnvironment companyId：用户ID
     *                           imgUrl：环境图片
     * @return R.ok();
     */
    @PostMapping("/commitCompanyEnvironment")
    public R commitCompanyEnvironment(@RequestBody CompanyEnvironment companyEnvironment) {
        if (companyEnvironment.getCompanyId() == null || companyEnvironment.getCompanyId().equals("")) {
            return R.error("缺少用户ID");
        }
        Member memberById = memberService.selectMemberById(companyEnvironment.getCompanyId());
        if (memberById.getIsCompany() == 0) {
            return R.error("您不是企业无法上传");
        }
//        companyEnvironmentService.deleteCompanyEnvironmentByCompanyId(companyEnvironment.getCompanyId());
        if (companyEnvironment.getImgUrl() != null) {
            String[] split = companyEnvironment.getImgUrl().split(",");
            for (int i = 0; i < split.length; i++) {
                if (split[i] != null && !split[i].equals("")) {
                    CompanyEnvironment environment = new CompanyEnvironment();
                    environment.setCompanyId(companyEnvironment.getCompanyId());
                    environment.setImgUrl(split[i]);
                    environment.setCreateAt(new Date());
                    companyEnvironmentService.insertCompanyEnvironment(environment);
                }
            }
        }
        return R.ok();
    }

    /**
     * 获取公司环境图片列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId：用户ID
     * @return R.ok();
     */
    @GetMapping("/getCompanyEnvironmentList")
    public R getCompanyEnvironmentList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                       String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member memberById = memberService.selectMemberById(memberId);
        if (memberById == null) {
            return R.error("请先注册");
        }
        HashMap<String, Object> map = new HashMap<>();
        CompanyEnvironment companyEnvironment = new CompanyEnvironment();
            companyEnvironment.setCompanyId(memberId);
            List<CompanyEnvironment> environmentList2 = companyEnvironmentService.selectCompanyEnvironmentList(companyEnvironment);
            //是否设置轮播图：0-否，1-是
            for (CompanyEnvironment CE : environmentList2) {
                CompanyCarousel carouselByImgId = companyCarouselService.selectCompanyCarouselByImgId(CE.getId());
                if (carouselByImgId != null) {
                    CE.setIsRotation(1);
                } else {
                    CE.setIsRotation(0);
                }
            }
            // 公司环境图片列表
            map.put("total",environmentList2.size());
            map.put("data",environmentList2);
            return R.ok(map);

    }

    /**
     * 删除公司环境图片
     *
     * @param memberId：用户ID
     * @param backgroundId：图片ID
     *
     * @return R.ok();
     */
    @GetMapping("/deleteCompanyEnvironment")
    public R deleteCompanyEnvironment(String memberId, String backgroundId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (backgroundId == null || backgroundId.equals("")) {
            return R.error("缺少图片ID");
        }
        companyEnvironmentService.deleteCompanyEnvironmentById(backgroundId);
        // 删除轮播图的公司环境
        companyCarouselService.deleteCompanyCarouselByImgId(backgroundId);
        return R.ok();
    }

    /**
     * 提交产品图片
     *
     * @param companyProduct companyId：用户ID
     *                       product：产品名称
     *                       imgUrl：产品图片
     *                       content：产品详情
     * @return R.ok();
     */
    @PostMapping("/commitProductImage")
    public R commitProductImage(@RequestBody CompanyProduct companyProduct) {
        if (companyProduct.getCompanyId() == null || companyProduct.getCompanyId().equals("")) {
            return R.error("缺少用户ID");
        }
        if (companyProduct.getImgUrl() != null) {
            String[] split = companyProduct.getImgUrl().split(",");
            for (int i = 0; i < split.length; i++) {
                if (split[i] != null && !split[i].equals("")) {
                    CompanyProduct product = new CompanyProduct();
                    product.setCompanyId(companyProduct.getCompanyId());
                    product.setProduct(companyProduct.getProduct());
                    product.setImgUrl(split[i]);
                    product.setCreateAt(new Date());
                    product.setContent(companyProduct.getContent());
                    companyProductService.insertCompanyProduct(product);
                }
            }
        }
        return R.ok();
    }

    /**
     * 获取产品图片列表
     *
     * @param memberId：用户ID
     * @return R.ok();
     */
    @GetMapping("/getProductImageList")
    public R getProductImageList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                 String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member memberById = memberService.selectMemberById(memberId);
        if (memberById == null) {
            return R.error("请先注册");
        }
        HashMap<String, Object> map = new HashMap<>();
        CompanyProduct companyProduct = new CompanyProduct();
        companyProduct.setCompanyId(memberId);
        List<CompanyProduct> companyProductList2 = companyProductService.selectCompanyProductList(companyProduct);
        // 产品图片列表
        map.put("total",companyProductList2.size());
        map.put("data",companyProductList2);
        return R.ok(map);
    }

    /**
     * 删除产品图片
     *
     * @param memberId：用户ID
     * @param backgroundId：图片ID
     *
     * @return R.ok();
     */
    @GetMapping("/deleteProductImage")
    public R deleteProductImage(String memberId, String backgroundId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (backgroundId == null || backgroundId.equals("")) {
            return R.error("缺少图片ID");
        }
        companyProductService.deleteCompanyProductById(backgroundId);
        return R.ok();
    }

    @Autowired
    private IQuotationCollectService quotationCollectService;
    /**
     *  收藏/取消收藏 行情
     * @param memberId      用户ID
     * @param toQuotationId    被收藏的行情ID
     * @return R.ok();
     */
    @GetMapping("/collectQuotation")
    public R collectQuotation(String memberId,String toQuotationId){
        if(memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if(toQuotationId == null || toQuotationId.equals("")) {
            return R.error("缺少被收藏的求购ID");
        }
        // 查是否已收藏
        QuotationCollect quotationCollect = quotationCollectService.selectQuotatioCollectByMemberIdAndToQuotatioId(memberId, toQuotationId);
        if(quotationCollect != null ) {
            quotationCollectService.deleteQuotationCollectById(quotationCollect.getId());
            return R.ok("已取消收藏");
        }
        QuotationCollect collect = new QuotationCollect();
        collect.setMemberId(memberId);
        collect.setQuotationId(toQuotationId);
        collect.setCollectAt(new Date());
        return quotationCollectService.insertQuotationCollect(collect)>0?R.ok("收藏成功"):R.error("收藏失败");
    }

    /**
     * 关注行情列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/followTheMarket")
    public R followTheMarket(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                             @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                             String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
//        PageInfo<QuotationCollect> pageInfo = quotationService.getQuotation(pageNum, pageSize, memberId);
        // 取消关注行情数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setFollowQuotationNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        PageInfo<Quotation> pageInfo = quotationService.getQuotationListByMemberId(pageNum, pageSize, memberId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo);
        return R.ok(map);
    }

    /**
     * 关注行情-关注的人发布的列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param followMemberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getFocusOnMarketByFollowMemberId")
    public R getFocusOnMarketByFollowMemberId(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                              @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                              String followMemberId) {
        if (followMemberId == null || followMemberId.equals("")) {
            return R.error("缺少用户ID");
        }
        PageInfo<Quotation> pageInfo = quotationService.getFocusOnMarketByFollowMemberId(pageNum, pageSize, followMemberId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo);
        return R.ok(map);
    }

    @Autowired
    private IJiaqinSupplyCollectService jiaqinSupplyCollectService;
    /**
     * 关注供应列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/focusOnSupply")
    public R focusOnSupply(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "100", required = false) Integer pageSize,
                           String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
//        PageInfo<JiaqinSupplyCollect> pageInfo = supplyService.getFocusOnSupply(pageNum, pageSize, memberId);
        // 取消关注供应数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setFollowSupplyNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        PageInfo<Supply> pageInfo = supplyService.getSupplyListByMemberId(pageNum, pageSize, memberId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo);
        return R.ok(map);
    }

    /**
     * 关注供应-关注的人发布的列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param followMemberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getFocusOnSupplyByFollowMemberId")
    public R getFocusOnSupplyByFollowMemberId(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                              @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                              String followMemberId) {
        if (followMemberId == null || followMemberId.equals("")) {
            return R.error("缺少用户ID");
        }
        PageInfo<Supply> pageInfo = supplyService.getFocusOnSupplyByFollowMemberId(pageNum, pageSize, followMemberId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo);
        return R.ok(map);
    }

    @Autowired
    private IWantToBuyCollectService wantToBuyCollectService;
    /**
     *  收藏/取消收藏求购
     * @param memberId      用户ID
     * @param toWantToBuyId    被收藏的求购ID
     * @return R.ok();
     */
    @GetMapping("/collectWantToBuy")
    public R collectWantToBuy(String memberId,String toWantToBuyId){
        if(memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if(toWantToBuyId == null || toWantToBuyId.equals("")) {
            return R.error("缺少被收藏的求购ID");
        }
        // 查是否已收藏
        WantToBuyCollect wantToBuyCollect = wantToBuyCollectService.selectBuyCollectByMemberIdAndToWantToBuyId(memberId, toWantToBuyId);
        if(wantToBuyCollect != null ) {
            wantToBuyCollectService.deleteWantToBuyCollectById(wantToBuyCollect.getId());
            return R.ok("已取消收藏");
        }
        WantToBuyCollect collect = new WantToBuyCollect();
        collect.setMemberId(memberId);
        collect.setWantToBuyId(toWantToBuyId);
        collect.setCollectAt(new Date());
        return wantToBuyCollectService.insertWantToBuyCollect(collect)>0?R.ok("收藏成功"):R.error("收藏失败");
    }

    /**
     * 关注求购列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/focusOnBuying")
    public R focusOnBuying(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                           String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
//        PageInfo<WantToBuyCollect> pageInfo = wantToBuyService.getFocusOnBuying(pageNum, pageSize, memberId);
        // 取消关注求购数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setFollowWantToBuyNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        PageInfo<WantToBuy> pageInfo = wantToBuyService.getWantToBuyListByMemberId(pageNum, pageSize, memberId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo);
        return R.ok(map);
    }

    /**
     * 关注求购-关注的人发布的列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param followMemberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getFocusOnBuyingByFollowMemberId")
    public R getFocusOnBuyingByFollowMemberId(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                           String followMemberId) {
        if (followMemberId == null || followMemberId.equals("")) {
            return R.error("缺少用户ID");
        }
        PageInfo<WantToBuy> pageInfo = wantToBuyService.getFocusOnBuyingByFollowMemberId(pageNum, pageSize, followMemberId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo);
        return R.ok(map);
    }

    @Autowired
    private INewsFollowService newsFollowService;
    /**
     *  收藏/取消收藏新闻
     * @param memberId  用户ID
     * @param newsId    收藏的新闻ID
     * @return R.ok();
     */
    @GetMapping("/collectNewsFollow")
    public R collectNewsFollow(String memberId,String newsId){
        if(memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if(newsId == null || newsId.equals("")) {
            return R.error("缺少收藏的新闻ID");
        }
        // 查是否已收藏
        NewsFollow newsFollow = newsFollowService.selectNewsFollowByMemberIdAndNewsId(memberId, newsId);
        if(newsFollow != null ) {
            newsFollowService.deleteNewsFollowById(newsFollow.getId());
            return R.ok("已取消收藏");
        }
        NewsFollow follow = new NewsFollow();
        follow.setMemberId(memberId);
        follow.setNewsId(newsId);
        follow.setCreated(new Date());
        return newsFollowService.insertNewsFollow(follow)>0?R.ok("收藏成功"):R.error("收藏失败");
    }

    @Autowired
    private IJiaqinFollowMemberService jiaqinFollowMemberService;
    @Autowired
    private IJiaqinFollowCompanyService jiaqinFollowCompanyService;
    /**
     *  供应详情 关注/取消关注 人或是企业
     * @param memberId  用户ID
     * @param supplyId  供应详情ID
     * @return R.ok();
     */
    @GetMapping("/followSupplyDetailsMeCo")
    public R followSupplyDetailsMeCo(String memberId,String supplyId){
        if(memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if(supplyId == null || supplyId.equals("")) {
            return R.error("缺少供应详情ID");
        }
        // 查是否已关注
        Supply supplyById = supplyService.selectSupplyById(supplyId);// 供应
        if (supplyById != null) {
            Member memberById = memberService.selectMemberById(supplyById.getReleaseMember());// 用户
            if (memberById != null) {
                Company companyById = companyService.selectCompanyByMemberId(memberById.getId());// 企业
                // 有企业
                if (companyById != null) {
                    JiaqinFollowCompany jiaqinFollowCompany = jiaqinFollowCompanyService.selectJiaqinFollowMemberByMemberIdAndToCompanyId(memberId, companyById.getId());// 是否关注
                    // 已关注取消关注企业
                   if (jiaqinFollowCompany != null) {
                       jiaqinFollowCompanyService.deleteJiaqinFollowCompanyById(jiaqinFollowCompany.getId());
                       return R.ok("已取消关注");
                   } else {
                       // 关注企业
                       JiaqinFollowCompany followCompany = new JiaqinFollowCompany();
                       followCompany.setMemberId(memberId);
                       followCompany.setFollowCompanyId(companyById.getId());
                       followCompany.setFollowAt(new Date());
                       jiaqinFollowCompanyService.insertJiaqinFollowCompany(followCompany);
                   }
                } else {// 无企业
                    JiaqinFollowMember jiaqinFollowMember = jiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(memberId, supplyById.getReleaseMember());
                    // 已关注取消关注个人
                    if (jiaqinFollowMember != null) {
                        jiaqinFollowMemberService.deleteJiaqinFollowMemberById(jiaqinFollowMember.getId());
                        return R.ok("已取消关注");
                    } else {
                        // 关注个人
                        JiaqinFollowMember followMember = new JiaqinFollowMember();
                        followMember.setMemberId(memberId);
                        followMember.setFollowMemberId(supplyById.getReleaseMember());
                        followMember.setFollowAt(new Date());
                        jiaqinFollowMemberService.insertJiaqinFollowMember(followMember);
                    }
                }
            }
        }
        return R.ok("关注成功");
    }

    @Autowired
    private INewsService newService;
    /**
     * 收藏新闻列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getCollectNewsList")
    public R getCollectNewsList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                           String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
//        PageInfo<NewsFollow> pageInfo = newService.getCollectNewsList(pageNum, pageSize, memberId);
        PageInfo<News> pageInfo = newService.getNewsListByMemberId(pageNum, pageSize, memberId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo);
        return R.ok(map);
    }

    /**
     * 平台通知列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/platformNotification")
    public R platformNotification(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                  String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        PageInfo<PlatformNotification> pageInfo = platformNotificationService.getPlatformNotification(pageNum, pageSize, memberId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo);
        return R.ok(map);
    }

    /**
     * 根据ID查平台通知详情
     *
     * @param id 平台通知ID
     * @return R.ok();
     */
    @GetMapping("/notificationById")
    public R getPlatformNotification(String id) {
        if (id == null || id.equals("")) {
            return R.error("缺少平台通知ID");
        }
        PlatformNotification notificationById = platformNotificationService.selectPlatformNotificationById(id);
        return RFactory.generateR(notificationById);
    }

    @Autowired
    private IMessageUserService messageUserService;
    @Autowired
    private IMessageInfoService messageInfoService;
    @Autowired
    private IMemberService memberService;

    /**
     * 留言
     *
     * @param messageUser memberId：留言人ID
     *                    messageMemberId：被留言人ID
     *                    resId：供应ID或求购ID
     *                    type:0-供应 1-求购 2-其他
     * @return R.ok();
     */
    @PostMapping("/leavingMessage")
    public R leavingMessage(@RequestBody MessageUser messageUser) {
        if (messageUser.getMemberId() == null || messageUser.getMemberId().equals("")) {
            return R.error("缺少留言人ID");
        }
        if (messageUser.getMessageMemberId() == null || messageUser.getMessageMemberId().equals("")) {
            return R.error("缺少被留言人ID");
        }
        if (messageUser.getResId() == null || messageUser.getResId().equals("")) {
            return R.error("缺少相关资源ID");
        }
        if (messageUser.getMemberId().equals(messageUser.getMessageMemberId())) {
            return R.error("不能和自己留言");
        }
        Member memberById1 = memberService.selectMemberById(messageUser.getMemberId());// 查留言人用户
        Member memberById2 = memberService.selectMemberById(messageUser.getMessageMemberId());// 查被留言人用户
        String teams_id = UUID.randomUUID().toString().replace("-", "");// 聊天室ID

        Integer type = 2;
        Supply supplyById = supplyService.selectSupplyById(messageUser.getResId());// 根据相关资源ID查供应
        WantToBuy wantToBuyById = wantToBuyService.findWantToBuyById(messageUser.getResId());// 根据相关资源ID查求购
        if (supplyById != null) {
            type = 0;
        } else if (wantToBuyById != null){
            type = 1;
        } else {
            type = 2;
        }

        MessageUser chat1By2Id = messageUserService.chat1By2Id(messageUser.getMemberId(), messageUser.getMessageMemberId(), type);// 两人的聊天室
        MessageUser mUser1 = new MessageUser();
        if (chat1By2Id == null) {
            mUser1.setMemberId(messageUser.getMemberId());
            if (memberById1 != null) {
                mUser1.setMemberName(memberById1.getUsername());
            }
            mUser1.setMessageMemberId(messageUser.getMessageMemberId());
            if (memberById2 != null) {
                mUser1.setMessageMemberName(memberById2.getUsername());
            }
            mUser1.setResId(messageUser.getResId());
            mUser1.setTeamsId(teams_id);
            mUser1.setNewMessage(messageUser.getNewMessage());
            mUser1.setType(type);
            messageUserService.insertMessageUser(mUser1);
        } else {
            mUser1.setId(chat1By2Id.getId());
            mUser1.setNewMessage(messageUser.getNewMessage());
            mUser1.setType(type);
            mUser1.setResId(messageUser.getResId());
            mUser1.setUpdatedTime(new Date());
            mUser1.setDelFlag(0);
            messageUserService.updateMessageUser(mUser1);
        }

        MessageUser chat2By2Id = messageUserService.chat2By2Id(messageUser.getMessageMemberId(), messageUser.getMemberId(), type);
        MessageUser mUser2 = new MessageUser();
        if (chat1By2Id == null) {
            mUser2.setMemberId(messageUser.getMessageMemberId());
            if (memberById2 != null) {
                mUser2.setMemberName(memberById2.getUsername());
            }
            mUser2.setMessageMemberId(messageUser.getMemberId());
            if (memberById1 != null) {
                mUser2.setMessageMemberName(memberById1.getUsername());
            }
            mUser2.setResId(messageUser.getResId());
            mUser2.setTeamsId(teams_id);
            mUser2.setNewMessage(messageUser.getNewMessage());
            mUser2.setUnreadNum(1);
            mUser2.setType(type);
            messageUserService.insertMessageUser(mUser2);
        } else {
            mUser2.setId(chat2By2Id.getId());
            mUser2.setNewMessage(messageUser.getNewMessage());
            mUser2.setUnreadNum(chat2By2Id.getUnreadNum() + 1);
            mUser2.setType(type);
            mUser2.setResId(messageUser.getResId());
            mUser2.setUpdatedTime(new Date());
            mUser2.setDelFlag(0);
            messageUserService.updateMessageUser(mUser2);
        }

        MessageUser teamsIdBy2Id = messageUserService.selectTeamsIdBy2Id(messageUser.getMemberId(), messageUser.getMessageMemberId(), type);
        MessageInfo mInfo = new MessageInfo();
        mInfo.setMemberId(messageUser.getMemberId());
        mInfo.setMessageMemberId(messageUser.getMessageMemberId());
        mInfo.setTeamsId(teamsIdBy2Id.getTeamsId());
        mInfo.setResId(messageUser.getResId());
        mInfo.setMessage(messageUser.getNewMessage());
        mInfo.setType(type);
        messageInfoService.insertMessageInfo(mInfo);

        return R.ok();
    }

    @Autowired
    private IQuotedPriceService quotedPriceService;
    /**
     * 供应、求购、名片通知联系人列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @param type  0-供应 1-求购 2-名片
     * @return R.ok();
     */
    @GetMapping("/getContactList")
    public R getContactList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                            @RequestParam(value = "pageSize", defaultValue = "5", required = false) Integer pageSize,
                            String memberId, Integer type) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        startPage();
        MessageUser messageUser = new MessageUser();
        messageUser.setMemberId(memberId);
        messageUser.setType(type);
        List<MessageUser> messageUserList = messageUserService.selectMessageUserList(messageUser);
        for (MessageUser MU : messageUserList) {
            Member memberMy = memberService.selectMemberById(MU.getMemberId());
            Member memberHe = memberService.selectMemberById(MU.getMessageMemberId());
            if (memberMy != null) {
                MU.setMyHeadPic(memberMy.getHeadpic());
            }
            if (memberHe != null) {
                // 查被留言人是否是企业
                Company companyByMemberId = companyService.selectCompanyByMemberId(MU.getMessageMemberId());
                if (companyByMemberId != null) {
                    MU.setMessageMemberType(1);
                    MU.setHeHeadPic(memberHe.getHeadpic());
                } else {
                    MU.setMessageMemberType(0);
                    MU.setHeHeadPic(memberHe.getHeadpic());
                }
            }
            // 求购留言列表 包含运费、不含运费价格
            if (type == 1) {
                QuotedPrice quotedPrice = quotedPriceService.selectQuotedPriceByWantToBuyId(MU.getResId(), memberId);
                if (quotedPrice != null) {
                    MU.setIncludingFreight(quotedPrice.getIncludingFreight());
                    MU.setExcludingFreight(quotedPrice.getExcludingFreight());
                }
            }
        }
        return RFactory.generateR(messageUserList);
    }

    /**
     * 进入聊天
     *
     * @param pageNum         页码
     * @param pageSize        每页数据量
     * @param memberId        用户ID
     * @param messageMemberId 被留言人ID
     * @param type            留言类型：0-供应 1-求购 2-其他
     * @return R.ok();
     */
    @GetMapping("/intoChatRoom")
    public R intoChatRoom(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "5", required = false) Integer pageSize,
                          String memberId, String messageMemberId, Integer type) {
        if (memberId == null || memberId.equals("") || messageMemberId == null || messageMemberId.equals("") || type == null) {
            return R.error("缺少用户ID");
        }
        if (memberId.equals(messageMemberId)) {
            return R.error("不能和自己留言");
        }
        MessageUser messageUser = new MessageUser();
        messageUser.setMemberId(memberId);
        messageUser.setMessageMemberId(messageMemberId);
        messageUser.setType(type);
        List<MessageUser> messageUserList = messageUserService.selectMessageUserList(messageUser);
        if (messageUserList.size() > 0) {
            MessageUser messageUserById = messageUserService.selectMessageUserById(messageUserList.get(0).getId());
            messageUser.setId(messageUserById.getId());
            messageUser.setUnreadNum(0);
            messageUserService.updateMessageUser(messageUser);

            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setTeamsId(messageUserById.getTeamsId());

//            startPage();
            List<MessageInfo> messageInfoList = messageInfoService.selectMessageInfoList(messageInfo);
            for (MessageInfo MI : messageInfoList) {
                Member memberMy = memberService.selectMemberById(MI.getMessageMemberId());
                Member memberHe = memberService.selectMemberById(MI.getMemberId());
                // 我的留言信息
                if (memberMy != null) {
//                    MI.setMyHeadPic(memberMy.getHeadpic());
                    Company myCompany = companyService.selectCompanyByMemberId(memberMy.getId());
                   if (myCompany != null) {
                       MI.setIsCompany(1);// 企业
                       MI.setMyHeadPic(memberMy.getHeadpic());// 企业头像
                       MI.setMemberCompanyId(myCompany.getId());// 企业ID
                   } else {
                       MI.setIsCompany(0);// 个人
                       MI.setMyHeadPic(memberMy.getHeadpic());// 个人头像
                       MI.setMemberCompanyId(memberMy.getId());// 个人ID
                   }
                }
                // 他的留言信息
                if (memberHe != null) {
//                    MI.setHeHeadPic(memberHe.getHeadpic());
//                    MI.setIsCompany(memberHe.getIsCompany());
                    Company heCompany = companyService.selectCompanyByMemberId(memberHe.getId());
                    if (heCompany != null) {
                        MI.setIsCompany(1);// 企业
                        MI.setHeHeadPic(memberHe.getHeadpic());// 企业头像
                        MI.setMemberCompanyId(heCompany.getId());// 企业ID
                    } else {
                        MI.setIsCompany(0);// 个人
                        MI.setHeHeadPic(memberHe.getHeadpic());// 个人头像
                        MI.setMemberCompanyId(memberHe.getId());// 个人ID
                    }
                }
                if (memberId.equals(MI.getMemberId())) {
                    MI.setIsMyspeak(1);// 是否是我的留言信息 0-不是 1-是
                } else {
                    MI.setIsMyspeak(0);// 为了分清每条信息显示在左还是右（类似聊天）
                }
            }

            startPage();
            ArrayList<MessageInfo> messageInfoArrayList = new ArrayList<>();
            for (MessageInfo MI : messageInfoList) {
                if (MI.getMemberId().equals(memberId) && MI.getMemberStatus() == 0) {
                    messageInfoArrayList.add(MI);
                } else if (MI.getMemberId().equals(messageMemberId) && MI.getMessageMemberStatus() == 0){
                    messageInfoArrayList.add(MI);
                }
            }

            return RFactory.generateR(messageInfoArrayList);
        } else {
            return R.ok();
        }
    }

    /**
     * 求购留言-头部信息
     *
     * @param memberId        用户ID
     * @param messageMemberId 被留言人ID
     * @return R.ok();
     */
    @GetMapping("/getWantToBuyTopInfo")
    public R getWantToBuyTopInfo(String memberId, String messageMemberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (messageMemberId == null || messageMemberId.equals("")) {
            return R.error("缺少被留言人ID");
        }
        MessageUser messageUser = new MessageUser();
        messageUser.setMemberId(memberId);
        messageUser.setMessageMemberId(messageMemberId);
        messageUser.setType(1);
        List<MessageUser> messageUserList = messageUserService.selectMessageUserList(messageUser);
        HashMap<String, Object> map = new HashMap<>();
        if (messageUserList.size() > 0) {
            WantToBuy wantToBuyById = wantToBuyService.selectWantToBuyById(messageUserList.get(0).getResId());
            if (wantToBuyById.getTitle() == null) {
                map.put("title","暂无");// 求购标题
            } else {
                map.put("title",wantToBuyById.getTitle());// 求购标题
            }

            // 求购留言 包含运费、不含运费价格
            QuotedPrice quotedPrice = quotedPriceService.selectQuotedPriceByWantToBuyId(wantToBuyById.getId(),memberId);
            if (quotedPrice != null) {
                map.put("includingFreight",quotedPrice.getIncludingFreight());// 包含运费
                map.put("excludingFreight",quotedPrice.getExcludingFreight());// 不含运费
                map.put("addr",quotedPrice.getAddr());// 货源地
                map.put("releaseTime",quotedPrice.getQuotedTime());// 求购时间
                // 卖家信息
                Member member = memberService.selectMemberById(quotedPrice.getQuotedMemberId());
                if (member != null) {
                    map.put("hedapic",member.getHeadpic());// 头像
                    map.put("username",member.getUsername());// 名字
                    map.put("mobile",member.getMobile());// 手机号
                    map.put("memberId",member.getId());// 用户ID
                    map.put("isCompany",member.getIsCompany());// 是否是企业：0-否 1-是
                }
            } else {
                QuotedPrice quotedPrice2 = quotedPriceService.selectQuotedPriceByWantToBuyId(wantToBuyById.getId(),messageMemberId);
                if (quotedPrice2 != null) {
                    map.put("includingFreight",quotedPrice2.getIncludingFreight());// 包含运费
                    map.put("excludingFreight",quotedPrice2.getExcludingFreight());// 不含运费
                    map.put("addr",quotedPrice2.getAddr());// 货源地
                    map.put("releaseTime",quotedPrice2.getQuotedTime());// 求购时间
                    // 卖家信息
                    Member member2 = memberService.selectMemberById(quotedPrice2.getQuotedMemberId());
                    if (member2 != null) {
                        map.put("hedapic",member2.getHeadpic());// 头像
                        map.put("username",member2.getUsername());// 名字
                        map.put("mobile",member2.getMobile());// 手机号
                        map.put("memberId",member2.getId());// 用户ID
                        map.put("isCompany",member2.getIsCompany());// 是否是企业：0-否 1-是
                    }
                }
            }
        }
        return RFactory.generateR(map);
    }

    /**
     * 供应通知详情-商品信息
     *
     * @param memberId        用户ID
     * @param messageMemberId 被留言人ID
     * @return R.ok();
     */
    @GetMapping("/getSupplyNoticeGoodsInfo")
    public R getSupplyNoticeGoodsInfo(String memberId, String messageMemberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (messageMemberId == null || messageMemberId.equals("")) {
            return R.error("缺少被留言人ID");
        }
        MessageUser messageUser = new MessageUser();
        messageUser.setMemberId(memberId);
        messageUser.setMessageMemberId(messageMemberId);
        messageUser.setType(0);
        List<MessageUser> messageUserList = messageUserService.selectMessageUserList(messageUser);
        HashMap<String, Object> map = new HashMap<>();
        if (messageUserList.size() > 0) {
            Supply supplyById = supplyService.selectSupplyById(messageUserList.get(0).getResId());
            String[] imgUrls = supplyById.getImgUrls().split(",");
            map.put("title",supplyById.getTitle());// 供应标题
            map.put("imgUrls",imgUrls[0]);// 供应图片
            map.put("price",supplyById.getPrice()+"元/"+supplyById.getUnit());// 供应价格
        }
        return RFactory.generateR(map);
    }

    /**
     * 求购通知详情-商品信息
     *
     * @param memberId        用户ID
     * @param messageMemberId 被留言人ID
     * @return R.ok();
     */
    @GetMapping("/getWantToBuyGoodsInfo")
    public R getWantToBuyGoodsInfo(String memberId, String messageMemberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (messageMemberId == null || messageMemberId.equals("")) {
            return R.error("缺少被留言人ID");
        }
        MessageUser messageUser = new MessageUser();
        messageUser.setMemberId(memberId);
        messageUser.setMessageMemberId(messageMemberId);
        messageUser.setType(1);
        List<MessageUser> messageUserList = messageUserService.selectMessageUserList(messageUser);
        HashMap<String, Object> map = new HashMap<>();
        if (messageUserList.size() > 0) {
            WantToBuy wantToBuyById = wantToBuyService.selectWantToBuyById(messageUserList.get(0).getResId());
            if (wantToBuyById.getTitle() == null) {
                map.put("title","暂无");// 求购标题
            } else {
                map.put("title",wantToBuyById.getTitle());// 求购标题
            }
            map.put("addr",wantToBuyById.getAddr());// 求购地址
            map.put("releaseTime",wantToBuyById.getReleaseTime());// 求购时间
            if (wantToBuyById.getExpectedPrice() == null) {
                map.put("expectedPrice","暂无");// 求购期望价格
            } else {
                map.put("expectedPrice",wantToBuyById.getExpectedPrice()+"元/斤");// 求购期望价格
            }
        }
        return RFactory.generateR(map);
    }

    /**
     * 根据ID置顶或删除聊天
     *
     * @param id   ID
     * @param type 0-置顶 1-删除
     * @return R.ok();
     */
    @GetMapping("/topOrDeleteChat")
    public R topOrDeleteChat(String id, Integer type) {
        if (id == null || id.equals("") || type == null) {
            return R.error("缺少ID");
        }
        MessageUser messageUser = new MessageUser();
        messageUser.setId(id);
        messageUser.setUpdatedTime(new Date());
        if (type == 1) {
            messageUser.setDelFlag(1);
            messageUser.setUnreadNum(0);
        }
        messageUserService.updateMessageUser(messageUser);
        return R.ok();
    }

    /**
     * 0-供应 1-求购 2-名片通知未读数
     *
     * @param memberId  用户ID
     * @return R.ok();
     */
    @GetMapping("/getNoticeUnread")
    public R getNoticeUnread(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Integer supplyUnread = messageUserService.supplyUnread(memberId, 0);
        Integer wantToBuyUnread = messageUserService.wantToBuyUnread(memberId, 1);
        Integer cardUnread = messageUserService.cardUnread(memberId, 2);
        HashMap<String, Object> map = new HashMap<>();
        if (supplyUnread != null) {
            map.put("supplyUnread",supplyUnread);// 供应通知未读数
        } else {
            map.put("supplyUnread",0);// 0
        }
        if (wantToBuyUnread != null) {
            map.put("wantToBuyUnread",wantToBuyUnread);// 求购通知未读数
        } else {
            map.put("wantToBuyUnread",0);// 0
        }
        if (cardUnread != null) {
            map.put("cardUnread",cardUnread);// 名片通知未读数
        } else {
            map.put("cardUnread",0);// 0
        }
        return R.ok(map);
    }

    @Autowired
    private ICardStyleBackgroundService cardStyleBackgroundService;

    /**
     * 名片样式-获取背景
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getBackground")
    public R getBackground(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        startPage();
        CardStyleBackground cardStyleBackground = new CardStyleBackground();
        cardStyleBackground.setMemberId(memberId);
        List<CardStyleBackground> backgroundList = cardStyleBackgroundService.selectCardStyleBackgroundList(cardStyleBackground);
        return RFactory.generateR(backgroundList);
    }

    /**
     * 名片样式-添加背景
     *
     * @param cardStyleBackground memberId 用户ID
     *                            headUrl 图片地址
     * @return R.ok();
     */
    @PostMapping("/uploadBackground")
    public R uploadBackground(@RequestBody CardStyleBackground cardStyleBackground) {
        if (cardStyleBackground.getMemberId() == null || cardStyleBackground.getMemberId().equals("")) {
            return R.error("缺少用户ID");
        }
        // 最大排序
        Integer maxSort = cardStyleBackgroundService.maxSort(cardStyleBackground.getMemberId());
        if (cardStyleBackground.getHeadUrl() != null && !cardStyleBackground.getHeadUrl().equals("")) {
            cardStyleBackground.setCreatedTime(new Date());
            cardStyleBackground.setUpdatedTime(new Date());
            cardStyleBackground.setSort(maxSort + 1);
            cardStyleBackgroundService.insertCardStyleBackground(cardStyleBackground);
        }
        return R.ok();
    }

    /**
     * 名片样式-删除背景
     *
     * @param memberId：用户ID
     * @param backgroundId：图片ID
     *
     * @return R.ok();
     */
    @GetMapping("/deleteBackgroundImg")
    public R deleteBackground(String memberId, String backgroundId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (backgroundId == null || backgroundId.equals("")) {
            return R.error("缺少图片ID");
        }
        CardStyleBackground background = cardStyleBackgroundService.selectCardStyleBackgroundById(backgroundId);
        if (background != null) {
            if (background.getStatus() == 1) {
                CardStyleBackground sort = cardStyleBackgroundService.findBackgroundByMemberIdAndSort(memberId);
                CardStyleBackground styleBackground = new CardStyleBackground();
                styleBackground.setId(sort.getId());
                styleBackground.setStatus(1);
                cardStyleBackgroundService.updateCardStyleBackground(styleBackground);
            }
            cardStyleBackgroundService.deleteCardStyleBackgroundById(backgroundId);
        }
        return R.ok();
    }

    /**
     * 名片样式-选择背景
     *
     * @param memberId     用户ID
     * @param backgroundId 背景图ID
     * @return R.ok();
     */
    @GetMapping("/choiceBackground")
    public R choiceBackground(String memberId, String backgroundId) {
        if (memberId == null || memberId.equals("") || backgroundId == null || backgroundId.equals("")) {
            return R.error("缺少用户ID");
        }
        CardStyleBackground cardStyleBackground = new CardStyleBackground();
        cardStyleBackground.setMemberId(memberId);
        List<CardStyleBackground> backgroundList = cardStyleBackgroundService.selectCardStyleBackgroundList(cardStyleBackground);
        if (backgroundList.size() == 0) {
            return R.error("请先上传再选择");
        } else {
            for (CardStyleBackground CSB : backgroundList) {
                CardStyleBackground background = new CardStyleBackground();
                background.setId(CSB.getId());
                if (CSB.getId().equals(backgroundId)) {
                    background.setStatus(1);
                } else {
                    background.setStatus(0);
                }
                cardStyleBackgroundService.updateCardStyleBackground(background);
            }
            return R.ok();
        }
    }

    @Autowired
    private ICardStyleShowService cardStyleShowService;

    /**
     * 名片样式-设置展示信息
     *
     * @param cardStyleShow memberId 用户ID
     *                      nameShow 展示姓名：0-不展示 1-展示
     *                      positionShow 展示职位：0-不展示 1-展示
     *                      companyShow 展示公司名：0-不展示 1-展示
     *                      headpicShow 展示头像：0-不展示 1-展示
     *                      mobileShow 展示电话号码：0-不展示 1-展示
     *                      mailboxShow 展示邮箱：0-不展示 1-展示
     *                      addressShow 展示地址：0-不展示 1-展示
     * @return R.ok();
     */
    @PostMapping("/setShowInformation")
    public R setShowInformation(@RequestBody CardStyleShow cardStyleShow) {
        if (cardStyleShow.getMemberId() == null || cardStyleShow.getMemberId().equals("")) {
            return R.error("缺少用户ID");
        }
        CardStyleShow styleShowByMemberId = cardStyleShowService.selectCardStyleShowByMemberId(cardStyleShow.getMemberId());
        if (styleShowByMemberId != null) {
            CardStyleShow styleShow = new CardStyleShow();
            styleShow.setId(styleShowByMemberId.getId());
            styleShow.setNameShow(cardStyleShow.getNameShow());
            styleShow.setPositionShow(cardStyleShow.getPositionShow());
            styleShow.setCompanyShow(cardStyleShow.getCompanyShow());
            styleShow.setHeadpicShow(cardStyleShow.getHeadpicShow());
            styleShow.setMobileShow(cardStyleShow.getMobileShow());
            styleShow.setMailboxShow(cardStyleShow.getMailboxShow());
            styleShow.setAddressShow(cardStyleShow.getAddressShow());
            cardStyleShowService.updateCardStyleShow(styleShow);
        } else {
            cardStyleShowService.insertCardStyleShow(cardStyleShow);
        }
        return R.ok();
    }

    /**
     * 名片样式-获取展示信息
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getShowInformation")
    public R getShowInformation(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        HashMap<String, Object> map = new HashMap<>();
        CardStyleShow styleShowByMemberId = cardStyleShowService.selectCardStyleShowByMemberId(memberId);
        if (styleShowByMemberId == null) {
            CardStyleShow cardStyleShow = new CardStyleShow();
            cardStyleShow.setMemberId(memberId);
            cardStyleShowService.insertCardStyleShow(cardStyleShow);
        } else {
            map.put("nameShow", styleShowByMemberId.getNameShow());
            map.put("positionShow", styleShowByMemberId.getPositionShow());
            map.put("companyShow", styleShowByMemberId.getCompanyShow());
            map.put("headpicShow", styleShowByMemberId.getHeadpicShow());
            map.put("mobileShow", styleShowByMemberId.getMobileShow());
            map.put("mailboxShow", styleShowByMemberId.getMailboxShow());
            map.put("addressShow", styleShowByMemberId.getAddressShow());
        }
        return RFactory.generateR(map);
    }

    @Autowired
    private INewsService newsService;

    /**
     * 我的新闻列表
     *
     * @param memberId 用户ID
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @return
     */
    @GetMapping("/getMyNewsList")
    public R getMyNewsList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                           String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        // 取消我的新闻数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setNewsNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        startPage();
        News news = new News();
        news.setMemberId(memberId);
        List<News> newsList = newsService.selectNewsList(news);
        if (newsList.size() > 0) {
            for (News Nl : newsList) {
                NewsImg newsImg = new NewsImg();
                newsImg.setNewsId(Nl.getId());
                List<NewsImg> imgList = newsImgService.selectNewsImgList(newsImg);
                Nl.setNewsImg(imgList);
            }
        }

        return RFactory.generateR(newsList);
    }

    @Autowired
    private INewsClassService newsClassService;

    /**
     * 获取行业新闻分类
     *
     * @return R.ok();
     */
    @GetMapping("/getNewsClassList")
    public R getNewsClassList() {
        HashMap<String, Object> map = new HashMap<>();
        List<NewsClass> newsClassList = newsClassService.selectNewsClassList(new NewsClass());
        map.put("list", newsClassList);
        return R.ok(map);
    }

    /**
     * 发布我的新闻
     *
     * @param news memberId：用户ID
     *             type：类型 0-文章,1-视频
     *             title：标题
     *             content：用户发布新闻内容
     *             newsClassId：新闻分类ID
     * @return
     */
    @PostMapping("/releaseMyNews")
    public R releaseMyNews(@RequestBody News news) {
        if (news.getMemberId() == null || news.getMemberId().equals("")) {
            return R.error("缺少用户ID");
        }
        if (news.getType() == 1) {
            return R.error("暂时未开放");
        }
        Member memberById = memberService.selectMemberById(news.getMemberId());
        if (memberById != null) {
            if (memberById.getNewsClose() == 1) {
                return R.error("权限关闭，请联系管理员");
            }
            news.setAuthor(memberById.getUsername());
            news.setProvince(memberById.getProvince());
            news.setCity(memberById.getCity());
            if (memberById.getArea() != null) {
                news.setArea(memberById.getArea());
            }
            // 添加我的新闻数字提示
            NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(news.getMemberId());
            if (numberTips != null) {
                NumberTips tips = new NumberTips();
                tips.setId(numberTips.getId());
                tips.setNewsNum(1);
                numberTipsService.updateNumberTips(tips);
            }
        }
        news.setReleaseAt(new Date());
        news.setPublisher(1);
        return newsService.insertNews(news) > 0 ? R.ok(news.getId()) : R.error("失败");
    }

    @Autowired
    private INewsImgService newsImgService;

    /**
     * 发布我的新闻-上传图片
     *
     * @param newsImg memberId：用户ID
     *                newsId：新闻ID
     *                pictureUrl：图片地址
     * @return
     */
    @PostMapping("/releaseMyNewsPicture")
    public R releaseMyNewsPicture(@RequestBody NewsImg newsImg) {
        if (newsImg.getMemberId() == null || newsImg.getMemberId().equals("")) {
            return R.error("缺少用户ID");
        }
        if (newsImg.getPictureUrl() != null) {
            String[] split = newsImg.getPictureUrl().split(",");
            for (int i = 0; i < split.length; i++) {
                newsImg.setPictureUrl(split[i]);
                newsImg.setUpdatedTime(new Date());
                newsImgService.insertNewsImg(newsImg);
            }
        }
        return R.ok();
    }

    @Autowired
    private IQuotationClassService questionClassService;

    /**
     * 获取市场行情通知
     *
     * @return R.ok();
     */
    @GetMapping("/getMarketInformationNotice")
    public R getMarketInformationNotice(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "3", required = false) Integer pageSize) {
        startPage();
        List<Quotation> quotationList = quotationService.findQuotationList(new Quotation());
        return RFactory.generateR(quotationList);
    }

    @Autowired
    private IMemberShareSloganService memberShareSloganService;

    /**
     * 获取用户分享标语
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getMemberShareSlogan")
    public R getMemberShareSlogan(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        MemberShareSlogan shareSlogan = new MemberShareSlogan();
        shareSlogan.setMemberId(memberId);
        List<MemberShareSlogan> memberShareSloganList = memberShareSloganService.selectMemberShareSloganList(shareSlogan);
        // 没有用户分享标语就创建
        if (memberShareSloganList.size() <= 0) {
            for (int i = 0; i < 3; i++) {
                shareSlogan.setMemberId(memberId);
                if (i == 0) {
                    shareSlogan.setSlogan("您好，这是我的电子名片，望惠存！");
                    shareSlogan.setIsChoice(1);
                    shareSlogan.setSort(1);
                } else if (i == 1) {
                    shareSlogan.setSlogan("这是我的电子名片，一键保存！");
                    shareSlogan.setIsChoice(0);
                    shareSlogan.setSort(2);
                } else {
                    shareSlogan.setSlogan("");
                    shareSlogan.setIsChoice(0);
                    shareSlogan.setSort(3);
                }
                memberShareSloganService.insertMemberShareSlogan(shareSlogan);
            }
        }
        shareSlogan.setIsChoice(1);
        List<MemberShareSlogan> list = memberShareSloganService.selectMemberShareSloganList(shareSlogan);
        return RFactory.generateR(list);
    }

    /**
     * 用户分享标语列表
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getMemberShareSloganList")
    public R getMemberShareSloganList(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        MemberShareSlogan shareSlogan = new MemberShareSlogan();
        shareSlogan.setMemberId(memberId);
        List<MemberShareSlogan> memberShareSloganList = memberShareSloganService.selectMemberShareSloganList(shareSlogan);
        if (memberShareSloganList.size() <= 0) {
            for (int i = 0; i < 3; i++) {
                shareSlogan.setMemberId(memberId);
                if (i == 0) {
                    shareSlogan.setSlogan("您好，这是我的电子名片，望惠存！");
                    shareSlogan.setIsChoice(1);
                    shareSlogan.setSort(1);
                } else if (i == 1) {
                    shareSlogan.setSlogan("这是我的电子名片，一键保存！");
                    shareSlogan.setIsChoice(0);
                    shareSlogan.setSort(2);
                } else {
                    shareSlogan.setSlogan("");
                    shareSlogan.setIsChoice(0);
                    shareSlogan.setSort(3);
                }
                memberShareSloganService.insertMemberShareSlogan(shareSlogan);
            }
        }
        List<MemberShareSlogan> list = memberShareSloganService.selectMemberShareSloganList(shareSlogan);
        return RFactory.generateR(list);
    }

    /**
     * 保存用户分享标语
     *
     * @param memberShareSlogan memberId：用户ID
     *                          id：选择展示分享标语的ID
     *                          slogan：标语
     * @return R.ok();
     */
    @PostMapping("/saveSlogan")
    public R saveSlogan(@RequestBody MemberShareSlogan memberShareSlogan) {
        if (memberShareSlogan.getMemberId() == null || memberShareSlogan.getMemberId().equals("")) {
            return R.error("缺少用户ID");
        }
        if (memberShareSlogan.getSlogan() != null && memberShareSlogan.getSlogan().length() > 30) {
            return R.error("分享标语太长");
        }
        MemberShareSlogan shareSlogan = new MemberShareSlogan();
        shareSlogan.setMemberId(memberShareSlogan.getMemberId());
        List<MemberShareSlogan> shareSloganList = memberShareSloganService.selectMemberShareSloganList(shareSlogan);
        for (MemberShareSlogan MSS : shareSloganList) {
            if (MSS.getId().equals(memberShareSlogan.getId())) {
                MSS.setId(MSS.getId());
                MSS.setIsChoice(1);
                MSS.setUpdatedTime(new Date());
                memberShareSloganService.updateMemberShareSlogan(MSS);
            } else {
                MSS.setId(MSS.getId());
                MSS.setIsChoice(0);
                MSS.setUpdatedTime(new Date());
                memberShareSloganService.updateMemberShareSlogan(MSS);
            }
            if (MSS.getSort() == 3) {
                shareSlogan.setId(MSS.getId());
                shareSlogan.setSlogan(memberShareSlogan.getSlogan());
                shareSlogan.setUpdatedTime(new Date());
                memberShareSloganService.updateMemberShareSlogan(shareSlogan);
            }
        }
        return R.ok();
    }

    /**
     * 名片样式-获取名片版式
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getCardStyle")
    public R getCardStyle(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        HashMap<String, Object> map = new HashMap<>();
        Member memberById = memberService.selectMemberById(memberId);
        if (memberById != null) {
            map.put("style", memberById.getStyle());
        }
        return R.ok(map);
    }

    /**
     * 名片样式-设置名片版式
     *
     * @param  id 用户ID
     * @param  style：版式
     * @return R.ok();
     */
    @GetMapping("/uploadCardStyle")
    public R uploadCardStyle(String id, Integer style) {
        if (id == null || id.equals("")) {
            return R.error("缺少用户ID");
        }
        Member member1 = new Member();
        member1.setId(id);
        member1.setStyle(style);
        memberService.updateMember(member1);
        return R.ok();
    }

    @Autowired
    private ICompanyService companyService;

    /**
     * 申请捆绑企业-查询企业列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param number 查询条件
     * @param type 查询类型：1-企业名 2-企业电话 3-企业号
     * @param memberId 用户id
     * @return R.ok();
     */
    @GetMapping("/selectCompanyList")
    public R selectCompanyList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                             String number, Integer type, String memberId) {
        // 企业
        Company company = new Company();
        company.setMemberId(memberId);
        if (type == 1) {
            company.setCompanyName(number);
        } else if (type == 2) {
            company.setCompanyPhone(number);
        } else {
            company.setCompanyNum(number);
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Company> list = companyService.selectCompanyList(company);
        PageInfo<Company> pageInfo = new PageInfo<>(list);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",pageInfo);
        return R.ok(map);
    }

//    /**
//     * 申请捆绑企业
//     *
//     * @param member id 用户ID
//     *               companyId：企业ID
//     * @return
//     */
//    @PostMapping("/applyBindCompany")
//    public R applyBindCompany(@RequestBody Member member) {
//        if (member.getId() == null || member.getId().equals("")) {
//            return R.error("缺少用户ID");
//        }
//        if (member.getCompanyId() == null || member.getCompanyId().equals("")) {
//            return R.error("请输入企业号");
//        }
//        Member memberById = memberService.selectMemberById(member.getId());
//        if (memberById == null || memberById.getIsCompany() == 1) {
//            return R.error("您已是企业无需绑定");
//        }
//        if (memberById.getIsVip() == 0 && memberById.getIsJqVip() == 0) {
//            return R.error("您不是会员，请先注册会员");
//        }
//        Company companyById = companyService.selectCompanyById(member.getCompanyId());
//        if (companyById == null) {
//            return R.error("未找到企业");
//        } else {
//            Member member1 = new Member();
//            member1.setId(member.getId());
//            member1.setCompanyId(member.getCompanyId());
//            // 改变公司信息
//            Member bindingId = memberService.selectMemberById(companyById.getMemberId());
//            if (bindingId != null) {
//                member1.setCorporation(companyById.getCompanyName());
//                if (bindingId.getIndustry() != null) {
//                    member1.setIndustry(bindingId.getIndustry());
//                }
//                if (bindingId.getPhilosophy() != null) {
//                    member1.setPhilosophy(bindingId.getPhilosophy());
//                }
//                if (bindingId.getBusiness() != null) {
//                    member1.setBusiness(bindingId.getBusiness());
//                }
//                if (bindingId.getBusinessId() != null) {
//                    member1.setBusinessId(bindingId.getBusinessId());
//                }
//                if (bindingId.getSynopsis() != null) {
//                    member1.setSynopsis(bindingId.getSynopsis());
//                }
//            }
//            memberService.updateMember(member1);
//        }
//        return R.ok();
//    }

    /**
     * 公司名片-联系我们-企业员工
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param companyId：企业ID
     * @return R.ok();
     */
    @GetMapping("/getCompanyStaff")
    public R getCompanyStaff(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                             @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                             String companyId) {
        if (companyId == null || companyId.equals("")) {
            return R.error("缺少企业ID");
        }
        startPage();
//        Member member = new Member();
//        member.setCompanyId(companyId);
//        List<Member> memberList = memberService.selectMemberList(member);
//        return RFactory.generateR(memberList);
        BundleApplication bundleApplication = new BundleApplication();
        bundleApplication.setCompanyId(companyId);
        bundleApplication.setStatus(1);
        List<BundleApplication> list = bundleApplicationService.selectBundleApplicationList(bundleApplication);
        for (BundleApplication BA : list) {
            Member member = memberService.selectMemberById(BA.getMemberId());
            if (member != null) {
                BA.setHeadpic(member.getHeadpic());
                BA.setMobile(member.getMobile());
                if (member.getName() != null) {
                    BA.setUsername(member.getName());
                } else {
                    BA.setUsername(member.getUsername());
                }
            }
        }
        return RFactory.generateR(list);
    }

    /**
     * 我的行情-删除按钮
     *
     * @param  memberId 用户ID
     * @param  quotationId：我的行情ID
     * @return R.ok();
     */
    @GetMapping("/deleteMyQuotation")
    public R deleteMyQuotation(String memberId, String quotationId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (quotationId == null || quotationId.equals("")) {
            return R.error("缺少我的行情ID");
        }
        return quotationService.deleteQuotationById(quotationId) >0 ? R.ok("删除成功") : R.error("删除失败");
    }

    /**
     * 修改用户信息
     * @param member id：用户ID
     *               headpic：头像
     *               name：姓名
     *               mobile：手机
     *               wechat：微信号
     *               mailbox：邮箱
     *               area：所在区域
     *               corporation：公司
     *               position：职位
     *               industry：行业
     *               philosophy；经营理念
     *               business：主营业务
     *               synopsis：主营介绍
     * @return R.ok();
     */
    @PostMapping("/updateUserInfo")
    public R updateUserInfo(@RequestBody Member member){
        if (member.getId() == null || member.getId().equals("")) {
            return R.error("缺少用户ID");
        }
        if (member.getName() == null || member.getName().equals("")) {
            return R.error("请输入姓名");
        }
        if (member.getMobile() == null || member.getMobile().equals("")) {
            return R.error("请输入手机号");
        }
        if (member.getCorporation() == null || member.getCorporation().equals("")) {
            return R.error("请输入公司");
        }
        if (member.getPosition() == null || member.getPosition().equals("")) {
            return R.error("请输入职位");
        }
        if (member.getIndustry() == null || member.getIndustry().equals("")) {
            return R.error("请选择行业");
        }
        Member memberById = memberService.selectMemberById(member.getId());
        Member member1 = new Member();
        member1.setId(member.getId());
        member1.setHeadpic(member.getHeadpic());
        member1.setName(member.getName());
        member1.setName(member.getName());
        member1.setMobile(member.getMobile());
        member1.setWechat(member.getWechat());
        member1.setMailbox(member.getMailbox());

        member1.setProvince(member.getProvince());
        member1.setProvinceName(member.getProvinceName());
        member1.setCity(member.getCity());
        member1.setCityName(member.getCityName());
        member1.setArea(member.getArea());
        member1.setAreaName(member.getAreaName());

        member1.setCorporation(member.getCorporation());
        member1.setPosition(member.getPosition());
        member1.setIndustry(member.getIndustry());
        member1.setPhilosophy(member.getPhilosophy());

        if (memberById.getBusinessId() == null || memberById.getBusiness() == null) {
            MemberBusiness memberBusiness = new MemberBusiness();
            memberBusiness.setIndustryId(member.getIndustry());
            memberBusiness.setDelFlag(0);
            List<MemberBusiness> businessList = memberBusinessService.selectMemberBusinessList(memberBusiness);
            if (businessList.size() > 0) {
                member1.setBusinessId(businessList.get(0).getId());
                member1.setBusiness(businessList.get(0).getBusinessName());
            }
        } else if (memberById.getIndustry() != null && !memberById.getIndustry().equals(member.getIndustry())){
            MemberBusiness memberBusiness = new MemberBusiness();
            memberBusiness.setIndustryId(member.getIndustry());
            memberBusiness.setDelFlag(0);
            List<MemberBusiness> businessList = memberBusinessService.selectMemberBusinessList(memberBusiness);
            if (businessList.size() > 0) {
                member1.setBusinessId(businessList.get(0).getId());
                member1.setBusiness(businessList.get(0).getBusinessName());
            }
        }

//        if (member.getBusinessId() != null) {
//            member1.setBusinessId(member.getBusinessId());
//            if (member.getBusinessId() != null && !member.getBusinessId().equals("")) {
//                String[] split = member.getBusinessId().split(",");// ,切割主营业务ID
//                String business = "";// 主营业务名称
//                for (int i = 0; i < split.length; i++) {
//                    MemberBusiness memberBusinessById = memberBusinessService.selectMemberBusinessById(split[i]);
//                    if (memberBusinessById != null) {
//                        business = business + memberBusinessById.getBusinessName() + ",";// 拼接主营业务名称
//                    }
//                }
//                member.setId(member.getId());
//                member.setBusiness(business);
//                memberService.updateMember(member);
//            }
//        }
//        member1.setBusiness(member.getBusiness());
        member1.setSynopsis(member.getSynopsis());
        member1.setLongitude(member.getLongitude());
        member1.setLatitude(member.getLatitude());
        member1.setAddress(member.getAddress());
        this.memberService.updateMember(member1);
        Company company = companyService.selectCompanyByMemberId(member.getId());
        if (company != null) {
            Company company1 = new Company();
            company1.setId(company.getId());
            if (!member.getHeadpic().equals("")) {
                company1.setCompanyAvatar(member.getHeadpic());
            }
            company1.setCompanyName(member.getCorporation());
            if (member.getAddress() != null) {
                company1.setCompanyAddr(member.getAddress());
            }
            if (member.getProvince() != null) {
                company1.setProvince((long)member.getProvince());
                company1.setProvinceName(member.getProvinceName());
                company1.setCity((long)member.getCity());
                company1.setCityName(member.getCityName());
                company1.setArea((long)member.getArea());
                company1.setAreaName(member.getAreaName());
            }
            if (member.getIndustry() != null) {
                company1.setIndustry(member.getIndustry());
            }
            company1.setCompanyPhone(member.getMobile());
            company1.setLatitude(member.getLatitude());
            company1.setLongitude(member.getLongitude());
            companyService.updateCompany(company1);
        }
        return R.ok();
    }

    @Autowired
    private ICompanyIndustryService companyIndustryService;
    /**
     * 企业-个人名片 搜索、根据类别、全国 获取个人名片列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @param memberName：用户名
     * @param province：省ID
     * @param city：市ID
     * @param area：区ID
     * @param industry：类别（行业）ID
     *
     * @return R.ok(map);
     */
    @GetMapping("/searchMemberCardList")
    public R searchMemberCardList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                  String memberId, String memberName, Integer province, Integer city, Integer area, String industry){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        HashMap<String,Object> map = new HashMap<>();
        Member member = new Member();
        member.setName(memberName);
        member.setProvince(province);
        member.setCity(city);
        member.setArea(area);
        member.setIndustry(industry);
        PageInfo<Member> pageInfo = memberService.searchMemberListPage(pageNum, pageSize, memberId, member);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    @Autowired
    private IMemberNewsLikesService memberNewsLikesService;
    @Autowired
    private ICompanyAutographService companyAutographicService;
    /**
     * 根据用户ID查询个人名片详情
     * @param memberId：用户ID
     * @return R.ok(map);
     */
    @GetMapping("/getPeopleCardByMemberId")
    public R getCompanyByMemberId(String memberId){
        if(memberId == null||memberId.equals("")){
            return R.error("缺少用户ID");
        }
        HashMap<String,Object> map = new HashMap<>();
        Member memberById = memberService.selectMemberById(memberId);
        // 名片信息展示设置
        CardStyleShow cardStyleShowByMemberId = cardStyleShowService.selectCardStyleShowByMemberId(memberId);
        memberById.setCardStyleShow(cardStyleShowByMemberId);

        // 名片信息背景
        CardStyleBackground cardStyleBackground = new CardStyleBackground();
        cardStyleBackground.setMemberId(memberId);
        cardStyleBackground.setStatus(1);
        List<CardStyleBackground> backgroundList = cardStyleBackgroundService.selectCardStyleBackgroundList(cardStyleBackground);
        if (backgroundList.size() > 0) {
            memberById.setCardStyleBackground(backgroundList.get(0));
        }
        // 展示编辑主营还是选择的主营
        if (memberById.getBusinessType() == 1) {
            memberById.setBusiness(memberById.getBusinessName());
        }

        map.put("member",memberById);// 个人名片信息

        // 捆绑公司信息
//        if (memberById.getCompanyId() != null) {
//            Company company = companyService.selectCompanyById(memberById.getCompanyId());
//            if (company != null) {
//                Member bindingMemberById = memberService.selectMemberById(company.getMemberId());
//                if (bindingMemberById != null) {
//                    memberById.setCompanyId(bindingMemberById.getId());
//                    memberById.setCorporation(company.getCompanyName());
//                    memberById.setPhilosophy(bindingMemberById.getPhilosophy());
//                    memberById.setCompanyAvatar(company.getCompanyAvatar());
//                }
//            }
//        }
        BundleApplication bundleApplication = bundleApplicationService.selectBundleApplicationByMemberId(memberId);
        if (bundleApplication != null && bundleApplication.getStatus() == 1) {
            Company company = companyService.selectCompanyById(bundleApplication.getCompanyId());
            if (company != null) {
                Member bindingMemberById = memberService.selectMemberById(company.getMemberId());
                memberById.setCompanyId(company.getMemberId());
                memberById.setCorporation(company.getCompanyName());
                memberById.setPhilosophy(bindingMemberById.getPhilosophy());
                memberById.setCompanyAvatar(company.getCompanyAvatar());
            }
        }

        // 内容数
        News news = new News();
        news.setMemberId(memberId);
        List<News> newsList = newService.selectNewsList(news);
        map.put("contentNum",newService.getAllNum(memberId));// 内容数
        // 新闻获赞数
        int likesNum = 0;
        if (newsList.size() > 0) {
            for (News N : newsList) {
                MemberNewsLikes memberNewsLikes = new MemberNewsLikes();
                memberNewsLikes.setNewsId(N.getId());
                List<MemberNewsLikes> newsLikesList = memberNewsLikesService.selectMemberNewsLikesList(memberNewsLikes);
                likesNum = likesNum + newsLikesList.size();
            }
        }
        map.put("likesNum",likesNum);// 新闻获赞数

        // 关注数
        JiaqinFollowCompany followCompany = new JiaqinFollowCompany();
        followCompany.setMemberId(memberId);
        List<JiaqinFollowCompany> followCompanyList = jiaqinFollowCompanyService.selectJiaqinFollowCompanyList(followCompany);
        JiaqinFollowMember followMember = new JiaqinFollowMember();
        followMember.setMemberId(memberId);
        List<JiaqinFollowMember> followMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(followMember);
        map.put("followNum",followCompanyList.size() + followMemberList.size());// 关注数

        // 粉丝数
        JiaqinFollowMember fansMember = new JiaqinFollowMember();
        fansMember.setFollowMemberId(memberId);
        List<JiaqinFollowMember> fansMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(fansMember);
        map.put("fansNum",fansMemberList.size());// 粉丝数

        // 产品展示
        CompanyProduct companyProduct = new CompanyProduct();
        companyProduct.setCompanyId(memberId);
        List<CompanyProduct> companyProductList = companyProductService.selectCompanyProductList(companyProduct);
        if (companyProductList.size() > 0) {
            map.put("companyProductList",companyProductList);// 产品展示
        } else {
            map.put("companyProductList",0);// 产品展示
        }

        // 个性签名
        CompanyAutograph companyAutograph = new CompanyAutograph();
        companyAutograph.setCompanyId(memberById.getCompanyId());
        List<CompanyAutograph> autographList = companyAutographicService.selectCompanyAutographList(companyAutograph);
        if (autographList.size() > 0) {
            map.put("autograph",autographList.get(0).getContent());// 个性签名
        } else {
            map.put("autograph",0);// 个性签名
        }
        return R.ok(map);
    }

    @Autowired
    private ICompanyInfoService companyInfoService;
    /**
     * 企业-个人名片 获取公司简介
     *
     * @param memberId：用户ID
     * @param toMemberId：被访问用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getCompanyInfo")
    public R getCompanyInfo(String memberId, String toMemberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        HashMap<String,Object> map = new HashMap<>();
        // 根据用户ID查企业
        Company companyByMemberId = companyService.selectCompanyByMemberId(toMemberId);
        // 被访问的是自己
        if (memberId.equals(toMemberId)) {
            if (companyByMemberId == null) {
                return R.error("您不是公司，请先申请");
            } else {
                CompanyInfo companyInfo = companyInfoService.selectCompanyInfoByCompanyId(toMemberId);
                companyInfo.setUploadShow(1);// 展示上传按钮
                map.put("data",companyInfo);
                return R.ok(map);
            }
        } else {// 被访问的不是自己
            if (companyByMemberId == null) {
                return R.error("他还不是公司，无法访问公司简介");
            } else {
                CompanyInfo companyInfo = companyInfoService.selectCompanyInfoByCompanyId(toMemberId);
                companyInfo.setUploadShow(0);// 不展示上传按钮
                map.put("data",companyInfo);
                return R.ok(map);
            }
        }
    }

    /**
     * 企业-个人名片 上传公司简介
     * @param companyInfo companyId：企业ID
     *                    title：标题
     *                    content：内容
     *                    videoUrl：视频地址
     *                    style：选择样式
     * @return R.ok();
     */
    @PostMapping("/uploadCompanyInfo")
    public R uploadCompanyInfo(@RequestBody CompanyInfo companyInfo){
        if (companyInfo.getCompanyId() == null || companyInfo.getCompanyId().equals("")) {
            return R.error("缺少企业ID");
        }
        CompanyInfo info = new CompanyInfo();
        info.setCompanyId(companyInfo.getCompanyId());
        List<CompanyInfo> companyInfoList = companyInfoService.selectCompanyInfoList(info);// 企业简介
        if (companyInfoList.size() > 0) {
            info.setId(companyInfoList.get(0).getId());
            info.setTitle(companyInfo.getTitle());
            info.setType(1);
            info.setContent(companyInfo.getContent());
            info.setIsVideo(1);
            info.setVideoUrl(companyInfo.getVideoUrl());
            info.setStyle(companyInfo.getStyle());
            companyInfoService.updateCompanyInfo(info);
        } else {
            companyInfoService.insertCompanyInfo(companyInfo);
        }
        return R.ok();
    }

    /**
     * 企业-个人名片 获取公司新闻
     *
     * @param companyId 企业ID
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @return
     */
    @GetMapping("/getCompanyNewsList")
    public R getCompanyNewsList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                           String companyId) {
        if (companyId == null || companyId.equals("")) {
            return R.error("缺少企业ID");
        }
        Company companyById = companyService.selectCompanyById(companyId);
        if (companyById != null) {
            startPage();
            News news = new News();
            news.setMemberId(companyById.getMemberId());
            List<News> newsList = newsService.selectNewsList(news);
            if (newsList.size() > 0) {
                for (News Nl : newsList) {
                    NewsImg newsImg = new NewsImg();
                    newsImg.setNewsId(Nl.getId());
                    List<NewsImg> imgList = newsImgService.selectNewsImgList(newsImg);
                    Nl.setNewsImg(imgList);
                }
            }
            return RFactory.generateR(newsList);
        }
        return R.ok();
    }

    /**
     * 企业-个人名片 获取个人我的资讯
     *
     * @param memberId 用户ID
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @return
     */
    @GetMapping("/getMemberNewsList")
    public R getMemberNewsList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少企业ID");
        }
        Member memberById = memberService.selectMemberById(memberId);
        if (memberById != null) {
            startPage();
            News news = new News();
            news.setMemberId(memberId);
            List<News> newsList = newsService.selectNewsList(news);// 新闻图片
            if (newsList.size() > 0) {
                for (News Nl : newsList) {
                    NewsImg newsImg = new NewsImg();
                    newsImg.setNewsId(Nl.getId());
                    List<NewsImg> imgList = newsImgService.selectNewsImgList(newsImg);
                    Nl.setNewsImg(imgList);
                }
            }
            return RFactory.generateR(newsList);
        }
        return R.ok();
    }

    @Autowired
    private IMemberSpreadBackgroundService memberSpreadBackgroundService;
    @Autowired
    private IShopConfigService shopConfigService;
    /**
     * 个人中心 获取我要推广
     *
     * @param memberId 用户ID
     *
     * @return
     */
    @GetMapping("/getMySpread")
    public R getMySpread(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        HashMap<String, Object> map = new HashMap<>();
        Member memberById = memberService.selectMemberById(memberId);
        if (memberById != null) {
            map.put("slogan",memberById.getSlogan());// 推广标语
            map.put("article",memberById.getArticle());// 推广内容
        }
        MemberSpreadBackground background = new MemberSpreadBackground();
        background.setMemberId(memberId);
        List<MemberSpreadBackground> spreadBackgroundList = memberSpreadBackgroundService.selectMemberSpreadBackgroundList(background);
        List<ShopConfig> shopConfigList = shopConfigService.selectShopConfigList(new ShopConfig());// 默认推广图
        if (spreadBackgroundList.size() > 0) {
            map.put("spreadBackground",spreadBackgroundList.get(0).getBackgroundUrl());// 推广图
            map.put("spreadBackgroundList",spreadBackgroundList);// 我的推广图列表
        } else {
            map.put("spreadBackground",shopConfigList.get(0).getShareImg());// 默认推广图
        }
        return R.ok(map);
    }

    /**
     * 个人中心 修改我要推广
     * @param memberSpreadBackground memberId：用户ID
     *                               slogan：推广标语
     *                               article：推广内容
     *                               backgroundUrl：推广背景图
     * @return R.ok();
     */
    @PostMapping("/uploadMySpread")
    public R uploadMySpread(@RequestBody MemberSpreadBackground memberSpreadBackground){
        if (memberSpreadBackground.getMemberId() == null || memberSpreadBackground.getMemberId().equals("")) {
            return R.error("缺少用户ID");
        }
        Member member = new Member();
        member.setId(memberSpreadBackground.getMemberId());
        // 推广标语
        if (memberSpreadBackground.getSlogan() == null || memberSpreadBackground.getSlogan().equals("")) {
            member.setSlogan(" ");
        } else {
            member.setSlogan(memberSpreadBackground.getSlogan());
        }
        // 推广内容
        if (memberSpreadBackground.getArticle() == null || memberSpreadBackground.getArticle().equals("")) {
            member.setArticle(" ");
        } else {
            member.setArticle(memberSpreadBackground.getArticle());
        }
        memberService.updateMember(member);
        // 删除我要推广背景图
        // memberSpreadBackgroundService.deleteMemberSpreadBackgroundByMemberId(memberSpreadBackground.getMemberId());
        // 背景图
        if (memberSpreadBackground.getBackgroundUrl() != null && !memberSpreadBackground.getBackgroundUrl().equals("")) {
            String[] split = memberSpreadBackground.getBackgroundUrl().split(",");// ,切割背景图地址
            for (int i = 0; i < split.length; i++) {
                MemberSpreadBackground spreadBackground = new MemberSpreadBackground();
                spreadBackground.setMemberId(memberSpreadBackground.getMemberId());
                spreadBackground.setBackgroundUrl(split[i]);
                spreadBackground.setSort(i);
                memberSpreadBackgroundService.insertMemberSpreadBackground(spreadBackground);
            }
        }
        return R.ok();
    }

    /**
     * 个人中心 立即设置
     *
     * @param memberId：用户ID
     * @param backgroundId：图片ID
     *
     * @return R.ok();
     */
    @GetMapping("/setNowMySpreadBackground")
    public R setNowMySpreadBackground(String memberId, String backgroundId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (backgroundId == null || backgroundId.equals("")) {
            return R.error("缺少图片ID");
        }
        List<MemberSpreadBackground> backgroundListByMemberId = memberSpreadBackgroundService.findSpreadBackgroundListByMemberId(memberId);
        MemberSpreadBackground spreadBackground = new MemberSpreadBackground();
        if (backgroundListByMemberId.size() > 0) {
            for (MemberSpreadBackground BLBM : backgroundListByMemberId) {
                spreadBackground.setId(BLBM.getId());
                if (BLBM.getId().equals(backgroundId)) {
                    spreadBackground.setStatus(1);// 状态：0-未选择 1-选择
                } else {
                    spreadBackground.setStatus(0);
                }
                memberSpreadBackgroundService.updateMemberSpreadBackground(spreadBackground);
            }
        }
        return R.ok();
    }

    /**
     * 个人中心 删除推广背景图
     *
     * @param memberId：用户ID
     * @param backgroundId：图片ID
     *
     * @return R.ok();
     */
    @GetMapping("/deleteNowMySpreadBackground")
    public R deleteNowMySpreadBackground(String memberId, String backgroundId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (backgroundId == null || backgroundId.equals("")) {
            return R.error("缺少图片ID");
        }
        memberSpreadBackgroundService.deleteMemberSpreadBackgroundById(backgroundId);
        return R.ok();
    }

    @Autowired
    private IJiaqinAdvertCooperateService jiaqinAdvertCooperateService;
    /**
     * 个人中心 我要合作列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getWantCooperateList")
    public R getWantCooperateList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                  String memberId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        // 取消我要合作数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setCooperateNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        startPage();
        List<JiaqinAdvertCooperate> advertCooperateList = jiaqinAdvertCooperateService.findAdvertCooperateList();
        return RFactory.generateR(advertCooperateList);
    }

    /**
     * 个人中心 根据ID查我要合作广告介绍
     *
     * @param memberId：用户ID
     * @param advertCooperateId：广告ID
     *
     * @return R.ok();
     */
    @GetMapping("/getWantCooperateInfo")
    public R getWantCooperateInfo(String memberId, String advertCooperateId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (advertCooperateId == null || advertCooperateId.equals("")) {
            return R.error("缺少广告ID");
        }
        JiaqinAdvertCooperate advertCooperateById = jiaqinAdvertCooperateService.selectJiaqinAdvertCooperateById(advertCooperateId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", advertCooperateById);
        return R.ok(map);
    }

    @Autowired
    private IJiaqinAdvertContractService jiaqinAdvertContractService;
    /**
     * 个人中心-我要合作 收合同
     *
     * @param memberId：用户ID
     * @param advertCooperateId：广告合作ID
     *
     * @return R.ok();
     */
    @GetMapping("/insertContract")
    public R insertContract(String memberId, String advertCooperateId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (advertCooperateId == null || advertCooperateId.equals("")) {
            return R.error("缺少广告ID");
        }
        JiaqinAdvertCooperate cooperateById = jiaqinAdvertCooperateService.selectJiaqinAdvertCooperateById(advertCooperateId);
        Member memberById = memberService.selectMemberById(memberId);
        JiaqinAdvertContract contractByMemberIdCooperateIdStatus = jiaqinAdvertContractService.findAdvertContractByMemberIdCooperateIdStatus(memberId, advertCooperateId, 0);
        if (contractByMemberIdCooperateIdStatus != null ) {
            return R.error("合同已存在未付款");
        } else {
            JiaqinAdvertContract advertContract = new JiaqinAdvertContract();
            advertContract.setCooperateId(advertCooperateId);
            advertContract.setCooperateName(cooperateById.getTitle());
            advertContract.setMemberId(memberId);
            advertContract.setMemberName(memberById.getUsername());
            advertContract.setMemberType(memberById.getIsCompany());
            advertContract.setPrice(cooperateById.getPrice());
            advertContract.setOrderNo(this.idGererateFactory.nextId().toString());
            jiaqinAdvertContractService.insertJiaqinAdvertContract(advertContract);
            // 添加我的合作数字提示
            NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
            if (numberTips != null) {
                NumberTips tips = new NumberTips();
                tips.setId(numberTips.getId());
                tips.setCooperateNum(1);
                numberTipsService.updateNumberTips(tips);
            }
        }
        return R.ok();
    }

    /**
     * 个人中心-我要合作 收合同列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param memberId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getContractList")
    public R getContractList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                             @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                             String memberId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        startPage();
        List<JiaqinAdvertContract> advertContractList = jiaqinAdvertContractService.findAdvertContractList(memberId);
        return RFactory.generateR(advertContractList);
    }

    /**
     * 个人中心-我要合作 合同详情
     *
     * @param memberId：用户ID
     * @param contractId：合同ID
     *
     * @return R.ok();
     */
    @GetMapping("/getContractInfo")
    public R getContractInfo(String memberId, String contractId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (contractId == null || contractId.equals("")) {
            return R.error("缺少合同ID");
        }
        JiaqinAdvertContract contract = jiaqinAdvertContractService.selectJiaqinAdvertContractById(contractId);
        return RFactory.generateR(contract);
    }

    @Resource
    private IdGererateFactory idGererateFactory;
    @Resource
    private IPayLogService payLogService;
    /**
     * 合同支付
     * @param memberId：用户ID
     * @param contractId：合同ID
     * @param req
     * @return
     */
    @GetMapping("/contractPay")
    public R contractPay(@RequestParam String memberId, String contractId, HttpServletRequest req){
        // 查询用户是否存在
        Member member = this.memberService.selectMemberById(memberId);
        if(member==null){
            return R.error("用户不存在");
        }
        // 查询订单是否存在
        // 获取合同价格
        JiaqinAdvertContract contractById = this.jiaqinAdvertContractService.selectJiaqinAdvertContractById(contractId);
        if (contractById == null) {
            return R.error("订单不存在");
        }

        HashMap<String, Object> map = new HashMap<>();
        //时间戳
        map.put("timeStamp", DateUtils.getNowDate().getTime()+"");

        //调用统一下单接口拿到prepay_id
        SortedMap<String, Object> date = new TreeMap<String,Object>();

        //返回用前端的date2
        SortedMap<String, Object> date2 = new TreeMap<String,Object>();
        date2.put("appId", AppBeanInjector.weixinConfig.getAppId());
        date2.put("timeStamp",DateUtils.getNowDate().getTime());
        date2.put("signType","MD5");

        date.put("appid",AppBeanInjector.weixinConfig.getAppId());
        date.put("attach","羽景科技合同支付");
        date.put("openid",member.getOpenid());
        date.put("body","羽景科技合同支付");
        date.put("mch_id",AppBeanInjector.weixinConfig.getMch_id());
        date.put("nonce_str",this.idGererateFactory.nextStringId());
        date.put("notify_url",AppBeanInjector.weixinConfig.getContract_pay_url());
        date.put("out_trade_no",contractById.getOrderNo()+"-"+this.idGererateFactory.nextStringId());
        date.put("spbill_create_ip", StringUtils.getRemoteAddr(req));
        float sessionmoney = Float.parseFloat(contractById.getPrice().toString());
        String finalmoney = String.format("%.2f", sessionmoney);
        finalmoney = finalmoney.replace(".", "");
        String newStr = finalmoney.replaceFirst("^0*", "");
        date.put("total_fee",newStr);
        date.put("trade_type","JSAPI");
        String perpayId = WeixinUtils.getPerpayId(date,date2);

        date2.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));

        map.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));
        //paySign 签名
        map.put("paySign",WeixinUtils.createSign(WeixinUtils.CHARSET,date2));
        //随机字符串
        map.put("nonceStr",date2.get("nonceStr"));

        //生成支付记录
        PayLog payLog = new PayLog();
        payLog.setOutTradeNo((String) date.get("out_trade_no"));
        payLog.setStatus(0);
        payLog.setType(2);// 支付类型: 0-订单支付 1-会员支付 2-合同支付
        payLog.setCreated(DateUtils.getNowDate());
        payLog.setMemberId(memberId);
        payLog.setResId(contractId);
        payLog.setPrice(contractById.getPrice());
        this.payLogService.insertPayLog(payLog);

        JiaqinAdvertContract advertContract = new JiaqinAdvertContract();
        advertContract.setId(contractId);
        advertContract.setOutTradeNo((String) date.get("out_trade_no"));
        jiaqinAdvertContractService.updateJiaqinAdvertContract(advertContract);

        return RFactory.generateR(map);
    }


    /**
     * 微信回调方法
     * @param req
     * @param res
     * @return
     */
    @PostMapping("/result")
    public Object vipResult(HttpServletRequest req, HttpServletResponse res){
        try {
            InputStream inStream = req.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            System.out.println("~~~~~~~~~~~~~~~~合同支付成功~~~~~~~~~");
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map<Object, Object> mapFromXml = WeixinUtils.doXMLParse(result);
            SortedMap<String ,String > sortedMap = new TreeMap();
            if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
                PayLog payLog = this.payLogService.selectPayLogByNo(mapFromXml.get("out_trade_no").toString());
                if(payLog.getStatus()==0){

                    String orderNo = mapFromXml.get("out_trade_no").toString().split("-")[0];
                    Date date = new Date();
//                    Member member = this.memberService.selectMemberById(memberId);
                    JiaqinAdvertContract byOrderNo = jiaqinAdvertContractService.findByOrderNo(orderNo);
                    if (byOrderNo == null){
                        sortedMap.put("return_code","FAIL");
                        sortedMap.put("return_msg","签名失败");
                        res.reset();
                        res.getWriter().write(parseXML(sortedMap));
                    }
                    //  验签成功后
                    // 合同改为已付款
                    JiaqinAdvertContract byOutTradeNo = jiaqinAdvertContractService.findByOrderNo(orderNo);

//                    JiaqinAdvertContract advertContract = new JiaqinAdvertContract();
//                    byOutTradeNo.setId(byOutTradeNo.getResId());
                    byOutTradeNo.setStatus(1);
                    byOutTradeNo.setUpdatedTime(date);
                    byOutTradeNo.setOutTradeNo(mapFromXml.get("out_trade_no").toString());
                    jiaqinAdvertContractService.updateJiaqinAdvertContract(byOutTradeNo);

                    // 更新支付记录
                    PayLog updatePayLog = new PayLog();
                    updatePayLog.setId(payLog.getId());
                    updatePayLog.setStatus(1);
                    this.payLogService.updatePayLog(updatePayLog);

                }
                sortedMap.put("return_code","SUCCESS");
                sortedMap.put("return_msg","OK");
                BufferedOutputStream out = new BufferedOutputStream(
                        res.getOutputStream());
                out.write(parseXML(sortedMap).getBytes());
                out.flush();
                out.close();

            }else {
                sortedMap.put("return_code","FAIL");
                sortedMap.put("return_msg","签名失败");
                BufferedOutputStream out = new BufferedOutputStream(
                        res.getOutputStream());
                out.write(parseXML(sortedMap).getBytes());
                out.flush();
                out.close();
            }
            return "success";
        } catch (Exception e) {
            return "failure";
        }
    }


    //输出XML
    public String parseXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>\n");
        Set es = map.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(null != v && !"".equals(v) && !"appkey".equals(k)) {

                sb.append("<" + k +"><![CDATA[" + v + "]]></" + k + ">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 个人中心-我的求购 收到的报价推荐
     *
     * @param memberId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getSupplyRecommendList")
    public R getSupplyRecommendList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                             @RequestParam(value = "pageSize", defaultValue = "5", required = false) Integer pageSize,
                             String memberId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        startPage();
        List<Supply> supplyList = supplyService.selectSupplyList(new Supply());
        for (Supply s : supplyList) {
            Member memberById = memberService.selectMemberById(s.getReleaseMember());
            if (memberById != null) {
                s.setMember(memberById);
                // 是否是企业
                Company company = companyService.selectCompanyByMemberId(s.getReleaseMember());
                if (company != null) {
                    s.setIsCompany(1);
                    s.setMemberName(company.getCompanyName());
                    s.setMemberCompanyId(company.getId());
                } else {
                    s.setIsCompany(0);
                    s.setMemberName(memberById.getUsername());
                    s.setMemberCompanyId(s.getReleaseMember());
                }
            }
            String[] split = s.getImgUrls().split(",");// ,切割图片路径
            if (split.length > 0) {
                s.setImgUrls(split[0]);// 取第一个
            }
        }
        return RFactory.generateR(supplyList);
    }

    /**
     * 关注行情-取消关注
     *
     * @param  memberId 用户ID
     * @param  id：关注的ID
     * @return R.ok();
     */
    @GetMapping("/deleteFollowQuotation")
    public R deleteFollowQuotation(String memberId, String id) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (id == null || id.equals("")) {
            return R.error("缺少关注行情的ID");
        }
        return quotationCollectService.deleteQuotationCollectById(id) >0 ? R.ok("删除成功") : R.error("删除失败");
    }

    /**
     * 关注供应-取消关注
     *
     * @param  memberId 用户ID
     * @param  id：关注的ID
     * @return R.ok();
     */
    @GetMapping("/deleteFollowSupply")
    public R deleteFollowSupply(String memberId, String id) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (id == null || id.equals("")) {
            return R.error("缺少关注供应的ID");
        }
        return jiaqinSupplyCollectService.deleteJiaqinSupplyCollectById(id) >0 ? R.ok("删除成功") : R.error("删除失败");
    }

    /**
     * 关注求购-取消关注
     *
     * @param  memberId 用户ID
     * @param  id：关注的ID
     * @return R.ok();
     */
    @GetMapping("/deleteFollowWantToBy")
    public R deleteFollowWantToBy(String memberId, String id) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (id == null || id.equals("")) {
            return R.error("缺少关注求购的ID");
        }
        return wantToBuyCollectService.deleteWantToBuyCollectById(id) >0 ? R.ok("删除成功") : R.error("删除失败");
    }

    @Autowired
    private IMemberBusinessService memberBusinessService;
    /**
     * 个人中心-主营业务列表
     *
     * @param pageNum：页码
     * @param pageSize：每页数据量
     * @param memberId：用户ID
     * @param industryId：行业ID
     *
     * @return R.ok();
     */
    @GetMapping("/getMemberBusinessList")
    public R getMemberBusinessList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                             @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                             String memberId, String industryId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        startPage();
        MemberBusiness memberBusiness = new MemberBusiness();
        memberBusiness.setIndustryId(industryId);
        memberBusiness.setStatus(1);
        memberBusiness.setDelFlag(0);
        List<MemberBusiness> businessList = memberBusinessService.selectMemberBusinessList(memberBusiness);
        for (MemberBusiness BL : businessList) {
            Member memberById = memberService.selectMemberById(memberId);
            if (memberById.getBusinessId() != null) {
                String[] split = memberById.getBusinessId().split(",");// ,切割主营业务ID
                for (int i = 0; i < split.length; i++) {
                    if (BL.getId().equals(split[i])) {
                        BL.setIsChoice(1);// 是否选择 0-否 1-是
                    }
                }
            }
        }
        return RFactory.generateR(businessList);
    }

    /**
     * 个人中心-修改主营业务
     *
     * @param member id：用户ID
     *               businessId：主营业务ID
     *
     * @return R.ok();
     */
    @PostMapping("/uploadMemberBusiness")
    public R uploadMemberBusiness(@RequestBody Member member){
        if (member.getId() == null || member.getId().equals("")) {
            return R.error("缺少用户ID");
        }

        if (member.getBusinessId() != null && !member.getBusinessId().equals("")) {
            String[] split = member.getBusinessId().split(",");// ,切割主营业务ID
            String business = "";// 主营业务名称
            for (int i = 0; i < split.length; i++) {
                MemberBusiness memberBusinessById = memberBusinessService.selectMemberBusinessById(split[i]);
                if (memberBusinessById != null) {
                    business = business + memberBusinessById.getBusinessName() + ",";// 拼接主营业务名称
                }
            }
            member.setId(member.getId());
            member.setIndustry(member.getIndustry());
            member.setBusiness(business);
            memberService.updateMember(member);
        }

        return R.ok();
    }

    @Autowired
    private ICompanyRecruitService companyRecruitService;
    @Autowired
    private IJiaqinQuestionService jiaqinQuestionService;
    @Autowired
    private INumberTipsService numberTipsService;
    /**
     * 我的-数字提示
     *
     * @param memberId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getMyNumTips")
    public R getMyNumTips(String memberId){
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
        if (numberTips == null) {
            NumberTips tips = new NumberTips();
            tips.setMemberId(memberId);
            numberTipsService.insertNumberTips(tips);
        }
        // 我的粉丝
        JiaqinFollowMember fansMember = new JiaqinFollowMember();
        fansMember.setFollowMemberId(memberId);
        List<JiaqinFollowMember> fansMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(fansMember);
        // 今日访客
        List<JiaqinVisitor> visitorList = jiaqinVisitorService.selectVisitorListByMemberId(memberId);
        // 我的行情
        Quotation quotation = new Quotation();
        quotation.setMemberId(memberId);
        List<Quotation> quotationList = quotationService.selectQuotationList(quotation);
        // 我的供应
        Supply supply = new Supply();
        supply.setReleaseMember(memberId);
        List<Supply> supplyList = supplyService.selectSupplyList(supply);
        // 我的求购
        WantToBuy wantToBuy = new WantToBuy();
        wantToBuy.setMemberId(memberId);
        List<WantToBuy> wantToBuyList = wantToBuyService.selectWantToBuyList(wantToBuy);
        // 我的招聘
        CompanyRecruit companyRecruit = new CompanyRecruit();
        companyRecruit.setCompanyId(memberId);
        List<CompanyRecruit> companyRecruitList = companyRecruitService.selectCompanyRecruitList(companyRecruit);
        // 我的新闻
        News news = new News();
        news.setMemberId(memberId);
        List<News> newsList = newsService.selectNewsList(news);
        // 我的提问
        JiaqinQuestion jiaqinQuestion = new JiaqinQuestion();
        jiaqinQuestion.setMemberId(memberId);
        List<JiaqinQuestion> questionList = jiaqinQuestionService.selectJiaqinQuestionList(jiaqinQuestion);
        // 关注行情
//        QuotationCollect quotationCollect = new QuotationCollect();
//        quotationCollect.setMemberId(memberId);
//        List<QuotationCollect> quotationCollectList = quotationCollectService.selectQuotationCollectList(quotationCollect);
        List<Quotation> quotationListByMemberId = quotationService.getQuotationListByMemberId2(memberId);
        // 关注供应
//        JiaqinSupplyCollect jiaqinSupplyCollect = new JiaqinSupplyCollect();
//        jiaqinSupplyCollect.setMemberId(memberId);
//        List<JiaqinSupplyCollect> supplyCollectList = jiaqinSupplyCollectService.selectJiaqinSupplyCollectList(jiaqinSupplyCollect);
        List<Supply> supplyListByMemberId = supplyService.getSupplyListByMemberId2(memberId);
        // 关注求购
//        WantToBuyCollect wantToBuyCollect = new WantToBuyCollect();
//        wantToBuyCollect.setMemberId(memberId);
//        List<WantToBuyCollect> wantToBuyCollectList = wantToBuyCollectService.selectWantToBuyCollectList(wantToBuyCollect);
        List<WantToBuy> wantToBuyListByMemberId = wantToBuyService.getWantToBuyListByMemberId2(memberId);
        // 我要合作
        List<JiaqinAdvertContract> advertContractList = jiaqinAdvertContractService.findAdvertContractList(memberId);
        HashMap<String, Object> map = new HashMap<>();
        if (numberTips.getFansNum() == 0) {
            map.put("myFansNum", 0);// 我的粉丝数
        } else {
            map.put("myFansNum", fansMemberList.size());// 我的粉丝数
        }
        if (numberTips.getVisitorNum() == 0) {
            map.put("visitorsTodayNum", 0);// 今日访客数
        } else {
            map.put("visitorsTodayNum", visitorList.size());// 今日访客数
        }
        if (numberTips.getQuotationNum() == 0) {
            map.put("myMarketNum", 0);// 我的行情数
        } else {
            map.put("myMarketNum", quotationList.size());// 我的行情数
        }
        if (numberTips.getSupplyNum() == 0) {
            map.put("mySupplyNum", 0);// 我的供应数
        } else {
            map.put("mySupplyNum", supplyList.size());// 我的供应数
        }
        if (numberTips.getWantToBuyNum() == 0) {
            map.put("myPurchaseNum", 0);// 我的求购数
        } else {
            map.put("myPurchaseNum", wantToBuyList.size());// 我的求购数
        }
        if (numberTips.getNewsNum() == 0) {
            map.put("myNewsNum",0);// 我的新闻数
        } else {
            map.put("myNewsNum",newsList.size());// 我的新闻数
        }
        if (numberTips.getQuestionsNum() == 0) {
            map.put("myQuestionNum",0);// 我的提问数
        } else {
            map.put("myQuestionNum",questionList.size());// 我的提问数
        }
        if (numberTips.getFollowQuotationNum() == 0) {
            map.put("followQuotationNum",0);// 关注行情数
        } else {
            map.put("followQuotationNum",quotationListByMemberId.size());// 关注行情数
        }
        if (numberTips.getFollowSupplyNum() == 0) {
            map.put("followSupplyNum",0);// 关注供应数
        } else {
            map.put("followSupplyNum",supplyListByMemberId.size());// 关注供应数
        }
        if (numberTips.getFollowWantToBuyNum() == 0) {
            map.put("followPurchaseNum",0);// 关注求购数
        } else {
            map.put("followPurchaseNum",wantToBuyListByMemberId.size());// 关注求购数
        }
        if (numberTips.getCooperateNum() == 0) {
            map.put("wantCooperateNum",0);// 我要合作数
        } else {
            map.put("wantCooperateNum",advertContractList.size());// 我要合作数
        }
//        map.put("myRecruitmentNum",companyRecruitList.size());// 我的招聘数
        return R.ok(map);
    }

    /**
     * 发布招聘
     * @param companyRecruit companyId：用户ID
     *                       title：招聘标题
     *                       salaryMin：最低薪资
     *                       salaryMax：最高薪资
     *                       industry：行业ID
     *                       province：工作省份ID
     *                       city：工作城市ID
     *                       area：工作区县ID
     *                       education：学历要求
     *                       experience：经验要求
     *                       peoNum：招聘人数
     *                       info：职位详情
     *                       phone：联系方式
     * @return R.ok();
     */
    @PostMapping("/publishRecruitment")
    public R publishRecruitment(@RequestBody CompanyRecruit companyRecruit){
        if (companyRecruit.getCompanyId() == null || companyRecruit.getCompanyId().equals("")) {
            return R.error("缺少用户ID");
        }
        Company company = companyService.selectCompanyByMemberId(companyRecruit.getCompanyId());
        if (company == null) {
            return R.error("您不是企业，不能发招聘");
        } else {
            companyRecruit.setCompanyId(company.getId());
            companyRecruit.setCompanyName(company.getCompanyName());
            companyRecruit.setSalaryUnit("元");
            companyRecruitService.insertCompanyRecruit(companyRecruit);
        }
        return R.ok();
    }

    @Autowired
    private INewsCommentLikersService newsCommentLikersService;
    /**
     * 用户 点赞/取消点赞 新闻评论
     * @param memberId：点赞用户ID
     * @param toMemberId：被点赞用户ID
     * @param commentId：评论ID
     * @return
     */
    @GetMapping("/likesNewsComment")
    public R likesNewsComment(String memberId, String toMemberId, String commentId) {
        NewsCommentLikers newsCommentLikers = new NewsCommentLikers();
        newsCommentLikers.setMemberId(memberId);
        newsCommentLikers.setToMemberId(toMemberId);
        newsCommentLikers.setNewsCommentId(commentId);
        List<NewsCommentLikers> commentLikersList = newsCommentLikersService.selectNewsCommentLikersList(newsCommentLikers);
        // 是否点赞
        if(commentLikersList.size() > 0) {
            // 取消点赞
            newsCommentLikersService.deleteNewsCommentLikersById(commentLikersList.get(0).getId());
            return R.ok("取消点赞");
        } else {
            // 点赞
            newsCommentLikersService.insertNewsCommentLikers(newsCommentLikers);
            return R.ok("点赞成功");
        }
    }

    /**
     * 判断用户是否是会员
     * @param memberId：用户ID
     * @return
     */
    @GetMapping("/getMemberIsVip")
    public R getMemberIsVip(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member memberById = memberService.selectMemberById(memberId);
        if (memberById != null) {
            if (memberById.getIsVip() == 0 && memberById.getIsJqVip() == 0) {
                return R.error("您还不是会员");
            }
        } else {
            return R.error("请先注册");
        }
        return R.ok();
    }

    /**
     * 注册会员、阅读权益详情
     * @param memberId：用户ID
     * @return
     */
    @GetMapping("/getVipEquityDetails")
    public R getVipEquityDetails(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        PlatformNotification platformNotification = new PlatformNotification();
        platformNotification.setStatus(0);
        platformNotification.setType(1);
        List<PlatformNotification> notificationList = platformNotificationService.selectPlatformNotificationList(platformNotification);
        return RFactory.generateR(notificationList.get(0).getContent());
    }

    /**
     * 举报新闻
     * @param memberId：用户ID
     * @param newsId：新闻ID
     * @return
     */
    @GetMapping("/complaintNews")
    public R complaintNews(String memberId, String newsId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (newsId == null || newsId.equals("")) {
            return R.error("缺少新闻ID");
        }
        News newsById = newService.selectNewsById(newsId);
        if (newsById != null) {
            News news = new News();
            news.setId(newsId);
            news.setComplaintNum(newsById.getComplaintNum() + 1);// 举报数+1
            newService.updateNews(news);
        }
        return R.ok();
    }

    /**
     * 名片夹-修改备注
     * @param memberId：用户ID
     * @param id：名片ID
     * @param type：类型：0:-企业名片 1-个人名片
     * @param remarks：备注
     * @return
     */
    @GetMapping("/modifyRemarks")
    public R modifyRemarks(String memberId, String id, Integer type, String remarks) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (id == null || id.equals("")) {
            return R.error("缺少名片ID");
        }
       if (type == null) {
           return R.error("缺少类型");
       }
       if (type == 0) {
           JiaqinFollowCompany jiaqinFollowCompany = new JiaqinFollowCompany();
           jiaqinFollowCompany.setId(id);
           if (remarks == null || remarks.equals("")) {
               jiaqinFollowCompany.setRemarks("0");
           } else {
               jiaqinFollowCompany.setRemarks(remarks);
           }
           jiaqinFollowCompanyService.updateJiaqinFollowCompany(jiaqinFollowCompany);
       } else {
           JiaqinFollowMember jiaqinFollowMember = new JiaqinFollowMember();
           jiaqinFollowMember.setId(id);
           if (remarks == null || remarks.equals("")) {
               jiaqinFollowMember.setRemarks("0");
           } else {
               jiaqinFollowMember.setRemarks(remarks);
           }
           jiaqinFollowMemberService.updateJiaqinFollowMember(jiaqinFollowMember);
       }
        return R.ok();
    }

    @Autowired
    private IVipConfigService vipConfigService;
    @Autowired
    private ICompanyApplyService companyApplyService;
    /**
     * 获取会员价格
     * @param memberId：用户ID
     * @param type：类型：0-个人 1-企业
     * @return
     */
    @GetMapping("/getVipConfig")
    public R getVipConfig(String memberId, Integer type) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member member = memberService.selectMemberById(memberId);
        if (member == null) {
            return R.error("请先注册");
        }
        HashMap<String, Object> map = new HashMap<>();
        VipConfig vipConfig = new VipConfig();
        // 注册个人会员
        if (type == 0) {
            // 判断是否是会员
            if (member.getIsVip() == 1 || member.getIsJqVip() == 1) {
                map.put("data",500);
                return R.ok(map);// 是会员提示
            } else {
                vipConfig.setType(0);
                List<VipConfig> vipConfigList = vipConfigService.selectVipConfigList(vipConfig);
                return RFactory.generateR(vipConfigList);// 不是会员弹出个人价格列表
            }
        } else if (type == 1){// 注册企业会员
            Company company = companyService.selectCompanyByMemberId(memberId);
            // 已是会员
            if (company != null) {
                map.put("data",500);
                return R.ok(map);// 是会员提示
            } else {
                // 判断有无企业申请
                CompanyApply companyApply = new CompanyApply();
                companyApply.setMemberId(memberId);
                List<CompanyApply> companyApplyList = companyApplyService.selectCompanyApplyList(companyApply);

                if (companyApplyList.size() > 0) {// 已申请
                    // 判断是否付款
                    if (companyApplyList.get(0).getPayStatus() == 0) {// 0 未支付
                        vipConfig.setType(1);
                        List<VipConfig> vipConfigList = vipConfigService.selectVipConfigList(vipConfig);
                        return RFactory.generateR(vipConfigList);// 弹出价格列表
                    } else if (companyApplyList.get(0).getPayStatus() == 1 && companyApplyList.get(0).getIsShow() == 0) {// 已支付
                        map.put("data", 1);
                        return R.ok(map);// 去申请企业入驻信息页面
                    } else {
                        return R.error("正在审核中");// 审核中提示
                    }
                } else {
                    vipConfig.setType(1);
                    List<VipConfig> vipConfigList = vipConfigService.selectVipConfigList(vipConfig);
                    return RFactory.generateR(vipConfigList);// 弹出企业价格列表
                }
            }
        }
        return R.ok();
    }

    /**
     * 会员支付
     * @param memberId：用户ID
     * @param vipId：会员配置ID
     * @param type：类型：0-个人 1-企业
     * @param req
     * @return
     */
    @GetMapping("/vipPay")
    public R vipPay(@RequestParam String memberId, String vipId, Integer type, HttpServletRequest req){
        // 查询用户是否存在
        Member member = this.memberService.selectMemberById(memberId);
        if(member == null) {
            return R.error("用户不存在");
        }

        // 获取会员价格
        VipConfig vipConfig = vipConfigService.selectVipConfigById(vipId);
        if (vipConfig == null) {
            return R.error("价格错误");
        }

        HashMap<String, Object> map = new HashMap<>();
        //时间戳
        map.put("timeStamp", DateUtils.getNowDate().getTime()+"");

        //调用统一下单接口拿到prepay_id
        SortedMap<String, Object> date = new TreeMap<String,Object>();

        //返回用前端的date2
        SortedMap<String, Object> date2 = new TreeMap<String,Object>();
        date2.put("appId", AppBeanInjector.weixinConfig.getAppId());
        date2.put("timeStamp",DateUtils.getNowDate().getTime());
        date2.put("signType","MD5");

        date.put("appid",AppBeanInjector.weixinConfig.getAppId());
        date.put("attach","羽景科技开通会员");
        date.put("openid",member.getOpenid());
        date.put("body","羽景科技开通会员");
        date.put("mch_id",AppBeanInjector.weixinConfig.getMch_id());
        date.put("nonce_str",this.idGererateFactory.nextStringId());
        date.put("notify_url",AppBeanInjector.weixinConfig.getVip_pay_url());
        date.put("out_trade_no",member.getOrderNo()+"-"+this.idGererateFactory.nextStringId());
        date.put("spbill_create_ip", StringUtils.getRemoteAddr(req));
        float sessionmoney = Float.parseFloat(vipConfig.getVipPrice().toString());
        String finalmoney = String.format("%.2f", sessionmoney);
        finalmoney = finalmoney.replace(".", "");
        String newStr = finalmoney.replaceFirst("^0*", "");
        date.put("total_fee",newStr);
        date.put("trade_type","JSAPI");
        String perpayId = WeixinUtils.getPerpayId(date,date2);

        date2.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));

        map.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));
        //paySign 签名
        map.put("paySign",WeixinUtils.createSign(WeixinUtils.CHARSET,date2));
        //随机字符串
        map.put("nonceStr",date2.get("nonceStr"));

        //生成支付记录
        PayLog payLog = new PayLog();
        payLog.setOutTradeNo((String) date.get("out_trade_no"));
        payLog.setStatus(0);
        payLog.setType(1);// 支付类型: 0-订单支付 1-会员支付 2-合同支付
        payLog.setCreated(DateUtils.getNowDate());
        payLog.setMemberId(memberId);
        payLog.setResId(vipId);
        payLog.setPrice(vipConfig.getVipPrice());
        payLog.setVip(vipConfig.getType());
        this.payLogService.insertPayLog(payLog);

        return RFactory.generateR(map);
    }


    /**
     * 会员微信回调方法
     * @param req
     * @param res
     * @return
     */
    @PostMapping("/vipCallBack")
    public Object vipCallBack(HttpServletRequest req, HttpServletResponse res){
        try {
            InputStream inStream = req.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            System.out.println("~~~~~~~~~~~~~~~~会员支付成功~~~~~~~~~");
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map<Object, Object> mapFromXml = WeixinUtils.doXMLParse(result);
            SortedMap<String ,String > sortedMap = new TreeMap();
            if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
                PayLog payLog = this.payLogService.selectPayLogByNo(mapFromXml.get("out_trade_no").toString());
                if(payLog.getStatus()==0){

                    String memberId = mapFromXml.get("out_trade_no").toString().split("-")[0];
                    Date date = new Date();
                    Member member = this.memberService.selectMemberByOrderOn(memberId);
                    System.out.println("~~~~~~~~~~~~~已查到用户~~~~~~~~~~~~");
                    if (member==null){
                        sortedMap.put("return_code","FAIL");
                        sortedMap.put("return_msg","签名失败");
                        res.reset();
                        res.getWriter().write(parseXML(sortedMap));
                    }
                    // 验签成功后
                    // 会员配置
                    VipConfig vipConfig = vipConfigService.selectVipConfigById(payLog.getResId());
                    // 会员信息 续费?年
                    Member update = new Member();
                    update.setId(member.getId());
                    if (vipConfig != null) {
                        if (vipConfig.getType() == 0) {
                            update.setIsVip(MemberIsVip.YES.getValue());

                            // 如果用户是会员 则 续费?年  否则 改为 当前时间续费?年
                            GregorianCalendar gregorianCalendar1 = new GregorianCalendar();
                            if(member.getIsVip().equals(MemberIsVip.YES.getValue())){
                                if (member.getVipEndTime() != null) {
                                    gregorianCalendar1.setTime(member.getVipEndTime());
                                } else {
                                    gregorianCalendar1.setTime(DateUtils.getNowDate());
                                }
                            }else{
                                gregorianCalendar1.setTime(DateUtils.getNowDate());
                            }
                            gregorianCalendar1.add(Calendar.YEAR,vipConfig.getVipTime());
                            update.setVipEndTime(gregorianCalendar1.getTime());
                        } else {
                            update.setIsJqVip(MemberIsVip.YES.getValue());

                            // 企业会员（先支付后填资料）
                            CompanyApply companyApply = new CompanyApply();
                            companyApply.setMemberId(member.getId());
                            List<CompanyApply> companyApplyList = companyApplyService.selectCompanyApplyList(companyApply);
                            // 有申请改企业申请表的付款状态
                            if (companyApplyList.size() > 0) {
                                companyApply.setId(companyApplyList.get(0).getId());
                                companyApply.setPayStatus(1);
                                companyApply.setIsShow(1);
                                companyApplyService.updateCompanyApply(companyApply);
                            } else {
                                companyApply.setPayStatus(1);
                                companyApply.setIsShow(0);
                                companyApplyService.insertCompanyApply(companyApply);
                            }


                            // 如果企业是会员 则 续费?年  否则 改为 当前时间续费?年
                            GregorianCalendar gregorianCalendar2 = new GregorianCalendar();
                            if(member.getIsJqVip().equals(MemberIsVip.YES.getValue())){
                                if (member.getJqVipEndTime() != null) {
                                    gregorianCalendar2.setTime(member.getJqVipEndTime());
                                } else {
                                    gregorianCalendar2.setTime(DateUtils.getNowDate());
                                }
                            }else{
                                gregorianCalendar2.setTime(DateUtils.getNowDate());
                            }
                            gregorianCalendar2.add(Calendar.YEAR,vipConfig.getVipTime());
                            update.setJqVipEndTime(gregorianCalendar2.getTime());
                        }
                    }
                    this.memberService.updateMember(update);
                    System.out.println("~~~~~~~~~~~~~已变成会员~~~~~~~~~~~~");

                    // 给推荐人返佣
                    Member introUser = memberService.selectMemberById(member.getIntroUser());// 推荐人信息
                    if (introUser != null) {
                        List<ShopConfig> shopConfigAll = shopConfigService.findAll();
                        HaoqiCoinRecord coinRecord = new HaoqiCoinRecord();
                        coinRecord.setMemberId(member.getIntroUser());
                        if (payLog.getVip() == 0) {
                            coinRecord.setNum(shopConfigAll.get(0).getVipPrice());
                            coinRecord.setGetType(1);
                        } else {
                            coinRecord.setNum(shopConfigAll.get(0).getVipReturnRatio());
                            coinRecord.setGetType(2);
                        }
                        coinRecord.setStatus(1);
                        coinRecord.setType(0);
                        coinRecord.setResId(member.getId());
                        coinRecordService.insertHaoqiCoinRecord(coinRecord);
                        System.out.println("~~~~~~~~~~~~~已给推荐人返佣~~~~~~~~~~~~");
                    }

                    //更新支付记录
                    PayLog updatePayLog = new PayLog();
                    updatePayLog.setId(payLog.getId());
                    updatePayLog.setStatus(1);
                    this.payLogService.updatePayLog(updatePayLog);
                    System.out.println("~~~~~~~~~~~~~已更新支付记录~~~~~~~~~~~~");

                    //发送订阅信息
                    String money = payLog.getPrice() + "元";
                    SendWxMessage.pushMemberPayment(member.getOpenid(), money);

                }
                sortedMap.put("return_code","SUCCESS");
                sortedMap.put("return_msg","OK");
                BufferedOutputStream out = new BufferedOutputStream(
                        res.getOutputStream());
                out.write(parseXML(sortedMap).getBytes());
                out.flush();
                out.close();

            }else {
                sortedMap.put("return_code","FAIL");
                sortedMap.put("return_msg","签名失败");
                BufferedOutputStream out = new BufferedOutputStream(
                        res.getOutputStream());
                out.write(parseXML(sortedMap).getBytes());
                out.flush();
                out.close();
            }
            return "success";
        } catch (Exception e) {
            return "failure";
        }
    }

    /**
     * test 8张名片背景
     * @return
     */
    @GetMapping("/test")
    public R test() {
        List<Member> list = memberService.selectMemberList(new Member());
        // 名片背景
        String backgroundImg1 = "https://imgjq.szyujingkeji.com/2021/10/21/b068b411ef9d8e0d807f6fc77ff5f671.jpg";
        String backgroundImg2 = "https://imgjq.szyujingkeji.com/2021/10/21/d3874e916f0ea5fd3ea853efa608e118.jpg";
        String backgroundImg3 = "https://imgjq.szyujingkeji.com/2021/10/21/420abe4496a26e07e69a38c82c2c9768.jpg";
        String backgroundImg4 = "https://imgjq.szyujingkeji.com/2021/10/21/266d9df843cd4f3a46141c2f1f8718d2.jpg";
        String backgroundImg5 = "https://imgjq.szyujingkeji.com/2021/10/21/d7ea434dab1a32ce92f541006c26fa79.jpg";
        String backgroundImg6 = "https://imgjq.szyujingkeji.com/2022/01/06/d9a385f817bc1bb35a42b18e67bfc655.png";
        String backgroundImg7 = "https://imgjq.szyujingkeji.com/2022/01/06/dd182d9f3af77a56be9f108c22a48d3f.png";
        String backgroundImg8 = "https://imgjq.szyujingkeji.com/2022/01/06/f35e840ad36044f3bf82f0760fa3ae9c.png";
        for (Member M : list) {
            for (int i = 1; i < 9; i++) {
                CardStyleBackground background = new CardStyleBackground();
                background.setMemberId(M.getId());
                if (i == 1) {
                    background.setHeadUrl(backgroundImg1);
                    background.setStatus(1);
                    background.setSort(1);
                } else if (i == 2) {
                    background.setHeadUrl(backgroundImg2);
                    background.setStatus(0);
                    background.setSort(2);
                } else if (i == 3) {
                    background.setHeadUrl(backgroundImg3);
                    background.setStatus(0);
                    background.setSort(3);
                } else if (i == 4) {
                    background.setHeadUrl(backgroundImg4);
                    background.setStatus(0);
                    background.setSort(4);
                } else if (i == 5) {
                    background.setHeadUrl(backgroundImg5);
                    background.setStatus(0);
                    background.setSort(5);
                } else if (i == 6) {
                    background.setHeadUrl(backgroundImg6);
                    background.setStatus(0);
                    background.setSort(6);
                } else if (i == 7) {
                    background.setHeadUrl(backgroundImg7);
                    background.setStatus(0);
                    background.setSort(7);
                } else {
                    background.setHeadUrl(backgroundImg8);
                    background.setStatus(0);
                    background.setSort(8);
                }
                cardStyleBackgroundService.insertCardStyleBackground(background);
            }
        }
        return R.ok();
    }

    @Autowired
    private IJiaqinAnswerReplyService jiaqinAnswerReplyService;
    /**
     * 问答-回复评论
     * @param memberId 用户ID
     * @param toMemberId  被回复用户ID
     * @param content   回复内容
     * @param commentId 评论ID
     * @return
     */
    @GetMapping("/replyComment")
    public R replyComment(String memberId,String toMemberId,String content,String commentId){
        if(memberId == null || memberId.equals("")){
            return R.error("用户ID不能为空");
        }
        if(toMemberId == null || toMemberId.equals("")){
            return R.error("被回复用户ID不能为空");
        }
        if(commentId == null || commentId.equals("")){
            return R.error("评论ID不能为空");
        }
        if(content == null || content.equals("")){
            return R.error("回复内容不能为空");
        }
        if(memberId.equals(toMemberId)){
            return R.error("不可回复自己");
        }
        JiaqinAnswerReply answerReply = new JiaqinAnswerReply();
        answerReply.setQuestionAnswerId(commentId);
        answerReply.setContent(content);
        answerReply.setFromUserId(memberId);
        answerReply.setToUserId(toMemberId);
        answerReply.setReplyAt(new Date());
        answerReply.setStatus(0);
        jiaqinAnswerReplyService.insertJiaqinAnswerReply(answerReply);
        return R.ok();
    }

    /**
     * 根据评论ID获取问答回复
     * @param questionAnswerId
     * @return
     */
    @GetMapping("/getReply")
    public R getReply(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String questionAnswerId){
        HashMap<String,Object> map = new HashMap<>();
        PageInfo pageInfo = jiaqinAnswerReplyService.selectAnswerReplyListByCommentId(pageNum,pageSize,questionAnswerId);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 联系我们-专属码
     * @param memberId：用户IDD
     * @return
     */
    @GetMapping("/getQrCode")
    public R getQrCode(String memberId) {
        if(memberId == null || memberId.equals("")){
            return R.error("用户ID不能为空");
        }
        Member member = memberService.selectMemberById(memberId);
        HashMap<String,Object> map = new HashMap<>();
        if (member == null) {
            return R.error("请先注册");
        } else {
            if(StringUtils.isBlank(member.getQrCode())) {
                String qrCode = WeixinUtils.getQrCodeImg(member);
                member.setQrCode(qrCode);
                Member update = new Member();
                update.setQrCode(qrCode);
                update.setId(memberId);
                this.memberService.updateMember(update);
            }
            map.put("data",member.getQrCode());
        }
        return R.ok(map);
    }

    /**
     * 是否是企业
     * @param memberId
     * @return
     */
    @GetMapping("/getIsCompany")
    public R getIsCompany(String memberId){
        HashMap<String,Object> map = new HashMap<>();
//        Company company = companyService.selectCompanyByMemberId(memberId);
        Member member = memberService.selectMemberById(memberId);
        if (member != null) {
            map.put("data",member.getIsCompany());
        }
        return R.ok(map);
    }

    @Autowired
    private IRegionService regionService;
    /**
     * 个人中心-我的招聘
     * @param memberId：用户ID
     * @param industryId：行业ID
     * @param province：省份ID
     * @param city：城市ID
     * @param area：区县ID
     * @return
     */
    @GetMapping("/getMyRecruitment")
    public R getMyRecruitment(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                              @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                              String memberId, String industryId, Long province, Long city, Long area){
        HashMap<String,Object> map = new HashMap<>();
        Company company = companyService.selectCompanyByMemberId(memberId);
        if (company != null) {
            CompanyRecruit companyRecruit = new CompanyRecruit();
            companyRecruit.setCompanyId(company.getId());
            companyRecruit.setIndustry(industryId);
            companyRecruit.setProvince(province);
            companyRecruit.setCity(city);
            companyRecruit.setArea(area);
            PageHelper.startPage(pageNum,pageSize);
            List<CompanyRecruit> companyRecruitList = companyRecruitService.selectCompanyRecruitList(companyRecruit);
            for (CompanyRecruit CR : companyRecruitList) {
                Company companyById = companyService.selectCompanyById(CR.getCompanyId());
                if (companyById != null) {
                    CR.setHeadpic(companyById.getCompanyAvatar());
                } else {
                    Member member = memberService.selectMemberById(memberId);
                    CR.setHeadpic(member.getHeadpic());
                }
                Region provinceName = regionService.selectRegionById(CR.getProvince());
                CR.setProvinceName(provinceName.getName());
                Region cityName = regionService.selectRegionById(CR.getCity());
                CR.setCityName(cityName.getName());
            }
            PageInfo<CompanyRecruit> pageInfo = new PageInfo<>(companyRecruitList);
            map.put("data",pageInfo);
        }
        return R.ok(map);
    }

    /**
     * 我的-我的新闻-删除
     * @param memberId：用户ID
     * @param newsId：新闻ID
     * @return
     */
    @GetMapping("/deleteMyNews")
    public R deleteMyNews(String memberId, String newsId){
        if(memberId == null || memberId.equals("")){
            return R.error("用户ID不能为空");
        }
        if(newsId == null || newsId.equals("")){
            return R.error("新闻ID不能为空");
        }
        News news = newService.selectNewsById(newsId);
        if (news != null) {
            // 我发布的新闻
            if (news.getMemberId().equals(memberId)) {
                newService.deleteNewsById(newsId);
            }
        }
        return R.ok();
    }

    /**
     * 我的-我的提问-删除
     * @param memberId：用户ID
     * @param questionsId：提问ID
     * @return
     */
    @GetMapping("/deleteMyQuestions")
    public R deleteMyQuestions(String memberId, String questionsId){
        if(memberId == null || memberId.equals("")){
            return R.error("用户ID不能为空");
        }
        if(questionsId == null || questionsId.equals("")){
            return R.error("提问ID不能为空");
        }
        JiaqinQuestion jiaqinQuestion = jiaqinQuestionService.selectJiaqinQuestionById(questionsId);
        if (jiaqinQuestion != null) {
            // 我发布的提问
            if (jiaqinQuestion.getMemberId().equals(memberId)) {
                jiaqinQuestionService.deleteJiaqinQuestionById(questionsId);
            }
        }
        return R.ok();
    }

    @Autowired
    private ICompanyCarouselService companyCarouselService;
    /**
     * 我的-公司环境-设置轮播图
     * @param memberId：用户ID
     * @param imgId：图片ID
     * @return
     */
    @GetMapping("/setRotationChart")
    public R setRotationChart(String memberId, String imgId){
        if(memberId == null || memberId.equals("")){
            return R.error("用户ID不能为空");
        }
        if(imgId == null || imgId.equals("")){
            return R.error("图片ID不能为空");
        }
        Company company = companyService.selectCompanyByMemberId(memberId);
        if (company != null) {
            // 企业环境
            CompanyEnvironment companyEnvironment = companyEnvironmentService.selectCompanyEnvironmentById(imgId);
            if (companyEnvironment != null) {
                // 企业轮播图
                CompanyCarousel companyCarousel = companyCarouselService.selectCompanyCarouselByImgId(imgId);
                if (companyCarousel != null) {
                    // 取消设置轮播图
                    companyCarouselService.deleteCompanyCarouselByImgId(imgId);
                    return R.ok("取消成功");
                } else {
                    // 设置轮播图
                    CompanyCarousel carousel = new CompanyCarousel();
                    carousel.setCompanyId(company.getId());
                    carousel.setImgId(imgId);
                    carousel.setImgUrl(companyEnvironment.getImgUrl());
                    companyCarouselService.insertCompanyCarousel(carousel);
                    return R.ok("设置成功");
                }
            }
        } else {
            return R.error("您还不是公司");
        }
        return R.ok();
    }

    @Autowired
    private IDownQuotationService downQuotationService;
    /**
     * 行情: 获取我的发布-绒
     * @param memberId：用户ID
     * @return
     */
    @GetMapping("/getMyQuotationVelvet")
    public R getMyQuotationVelvet(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,
                                  String memberId) {
        HashMap<String, Object> map = new HashMap<>();
        DownQuotation downQuotation = new DownQuotation();
        downQuotation.setMemberId(memberId);
        PageHelper.startPage(pageNum,pageSize);
        List<DownQuotation> list = downQuotationService.selectDownQuotationList(downQuotation);
        PageInfo<DownQuotation> pageInfo = new PageInfo<>(list);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 行情: 我的发布-绒-删除
     * @param memberId：用户ID
     * @param downId：绒行情ID
     * @return
     */
    @GetMapping("/deleteMyDownQuestions")
    public R deleteMyDownQuestions(String memberId, String downId){
        if(memberId == null || memberId.equals("")){
            return R.error("用户ID不能为空");
        }
        if(downId == null || downId.equals("")){
            return R.error("绒行情ID不能为空");
        }
        DownQuotation downQuotation = downQuotationService.selectDownQuotationById(downId);
        if (downQuotation != null) {
            // 我发布的绒行情
            if (downQuotation.getMemberId().equals(memberId)) {
                downQuotationService.deleteDownQuotationById(downId);
            }
        }
        return R.ok();
    }

    @Autowired
    private IModularShowService modularShowService;
    /**
     * 模块展示
     * @param
     * @return 类型：1-行情走势 2-名片大全 3-热门视频 4-企业招聘 5-问答知道 6-行业新闻
     */
    @GetMapping("/getModularShow")
    public R getModularShow(){
        HashMap<String,Object> map = new HashMap<>();
        map.put("data",modularShowService.selectModularShowList(new ModularShow()));
        return R.ok(map);
    }

    @Autowired
    private IMemberDepartmentService memberDepartmentService;
    /**
     * 申请捆绑企业部门列表
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/memberDepartmentList")
    public R memberDepartmentList(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        List<MemberDepartment> list = memberDepartmentService.selectMemberDepartmentList(new MemberDepartment());
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", list);
        return R.ok(map);
    }

    @Autowired
    private IMemberDutiesService memberDutiesService;
    /**
     * 申请捆绑企业职务列表
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/memberDutiesList")
    public R memberDutiesList(String memberId, String departmentId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (departmentId == null || departmentId.equals("")) {
            return R.error("无");
        }
        MemberDuties memberDuties = new MemberDuties();
        memberDuties.setDepartmentId(departmentId);
        List<MemberDuties> list = memberDutiesService.selectMemberDutiesList(memberDuties);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", list);
        return R.ok(map);
    }

    @Autowired
    private IBundleApplicationService bundleApplicationService;

    /**
     * 申请捆绑企业-加入企业
     *
     * @param bundleApplication memberId 用户ID
     *                      companyId 企业ID
     *                      departmentId 部门ID
     *                      dutiesId 职务ID
     *                      numPhone 搜索：1-企业号，2-手机号
     * @return R.ok();
     */
    @PostMapping("/joinCompany")
    public R joinCompany(@RequestBody BundleApplication bundleApplication) {
        if (bundleApplication.getMemberId() == null || bundleApplication.getMemberId().equals("")) {
            return R.error("缺少用户ID");
        }
        if (bundleApplication.getCompanyId() == null || bundleApplication.getCompanyId().equals("")) {
            return R.error("缺少企业号或手机号");
        }
        if (bundleApplication.getDepartmentId() == null || bundleApplication.getDepartmentId().equals("")) {
            return R.error("缺少部门ID");
        }
        if (bundleApplication.getDutiesId() == null || bundleApplication.getDutiesId().equals("")) {
            return R.error("缺少职务ID");
        }
        Company company = null;
        if (bundleApplication.getNumPhone() == 1) {
            company = companyService.selectCompanyByCompanyNum(bundleApplication.getCompanyId());
        } else if (bundleApplication.getNumPhone() == 2) {
            company = companyService.selectCompanyByCompanyPhone(bundleApplication.getCompanyId());
        }
        BundleApplication bundleApplicationByMemberId = bundleApplicationService.selectBundleApplicationByMemberId(bundleApplication.getMemberId());
        if (company == null) {
            return R.error("未找到该企业");
        } else if (bundleApplicationByMemberId != null) {
            return R.error("您已绑定或正在审核");
        } else {
            MemberDepartment memberDepartment = memberDepartmentService.selectMemberDepartmentById(bundleApplication.getDepartmentId());
            if (memberDepartment != null) {
                bundleApplication.setDepartmentName(memberDepartment.getName());
            }
            MemberDuties memberDuties = memberDutiesService.selectMemberDutiesById(bundleApplication.getDutiesId());
            if (memberDuties != null) {
                bundleApplication.setDutiesName(memberDuties.getDutiesName());
            }
            bundleApplication.setCompanyId(company.getId());
            bundleApplicationService.insertBundleApplication(bundleApplication);
            return R.ok("申请成功");
        }
    }

    /**
     * 申请捆绑企业-用户加入企业申请列表
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/bundleApplicationList")
    public R bundleApplicationList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                   String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Company company = companyService.selectCompanyByMemberId(memberId);
        HashMap<String, Object> map = new HashMap<>();
        if (company == null) {
            map.put("data", 1);
        } else {
            BundleApplication bundleApplication = new BundleApplication();
            bundleApplication.setCompanyId(company.getId());
            PageHelper.startPage(pageNum,pageSize);
            List<BundleApplication> list = bundleApplicationService.selectBundleApplicationList(bundleApplication);
            for (BundleApplication BA : list) {
                Member member = memberService.selectMemberById(BA.getMemberId());
                if (member != null) {
                    BA.setHeadpic(member.getHeadpic());
                    if (member.getName() != null) {
                        BA.setUsername(member.getName());
                    } else {
                        BA.setUsername(member.getUsername());
                    }
                }
            }
            PageInfo<BundleApplication> pageInfo = new PageInfo<>(list);
            map.put("data",pageInfo);
        }
        return R.ok(map);// data=1 去申请捆绑企业页面
    }

    /**
     * 申请捆绑企业-同意拒绝
     *
     * @param bundleApplicationId 申请ID
     * @param status 申请状态：1-通过 2-驳回
     * @return R.ok();
     */
    @GetMapping("/agreeOrRefuse")
    public R agreeOrRefuse(String bundleApplicationId, Integer status) {
        if (bundleApplicationId == null || bundleApplicationId.equals("")) {
            return R.error("缺少申请ID");
        }
        if (status == null) {
            return R.error("缺少申请状态");
        }
        BundleApplication bundleApplication = new BundleApplication();
        bundleApplication.setId(bundleApplicationId);
        bundleApplication.setStatus(status);
        bundleApplicationService.updateBundleApplication(bundleApplication);
        return R.ok();
    }

    /**
     * 申请捆绑企业-删除申请
     *
     * @param bundleApplicationId 申请ID
     * @return R.ok();
     */
    @GetMapping("/deleteBundleApplication")
    public R deleteBundleApplication(String bundleApplicationId) {
        if (bundleApplicationId == null || bundleApplicationId.equals("")) {
            return R.error("缺少申请ID");
        }
        bundleApplicationService.deleteBundleApplicationById(bundleApplicationId);
        return R.ok();
    }

    @Autowired
    private IJiaqinAdvertPlatformService jiaqinAdvertPlatformService;
    /**
     * 新闻广告-查询
     *
     * @param newsId 新闻ID
     * @return R.ok();
     */
    @GetMapping("/selectNewsAdvert")
    public R selectNewsAdvert(String newsId) {
        if (newsId == null || newsId.equals("")) {
            return R.error("缺少新闻ID");
        }
        JiaqinAdvertPlatform advertPlatformByResId = jiaqinAdvertPlatformService.selectJiaqinAdvertPlatformByResId(newsId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",advertPlatformByResId);
        return R.ok(map);
    }

    /**
     * 新闻广告-文本广告详情
     *
     * @param id ID
     * @return R.ok();
     */
    @GetMapping("/getTextAdvertInfo")
    public R getTextAdvertInfo(String id) {
        if (id == null || id.equals("")) {
            return R.error("缺少ID");
        }
        JiaqinAdvertPlatform advertPlatformByResId = jiaqinAdvertPlatformService.selectJiaqinAdvertPlatformById(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",advertPlatformByResId);
        return R.ok(map);
    }

    /**
     * 申请入驻-获取默认信息
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getDefaultInfo")
    public R getDefaultInfo(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member member = memberService.selectMemberById(memberId);
        HashMap<String, Object> map = new HashMap<>();
        if (member != null) {
            CompanyIndustry industry = companyIndustryService.selectCompanyIndustryById(member.getIndustry());
            if (industry != null) {
                member.setIndustryName(industry.getName());
            }
            map.put("data",member);
        }
        return R.ok(map);
    }

    /**
     * 主营业务-获取主营业务信息
     *
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/getBusinessInfo")
    public R getBusinessInfo(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member member = memberService.selectMemberById(memberId);
        HashMap<String, Object> map = new HashMap<>();
        if (member != null) {
            map.put("businessType",member.getBusinessType());
            map.put("businessName",member.getBusinessName());
        }
        return R.ok(map);
    }

    /**
     * 判断用户会员类型
     * @param memberId：用户ID
     * @return
     */
    @GetMapping("/getMemberVipType")
    public R getMemberVipType(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member memberById = memberService.selectMemberById(memberId);
        HashMap<String, Object> map = new HashMap<>();
        if (memberById != null) {
            if (memberById.getIsVip() == 1 && memberById.getIsJqVip() == 0) {
                map.put("memberVip",1);// 个人会员
            } else if (memberById.getIsVip() == 0 && memberById.getIsJqVip() == 1) {
                map.put("memberVip",2);// 企业会员
            } else if (memberById.getIsVip() == 1 && memberById.getIsJqVip() == 1) {
                map.put("memberVip",3);// 既是个人会员又是企业会员
            } else {
                map.put("memberVip",0);// 不是会员
            }
        } else {
            return R.error("请先注册");
        }
        return R.ok(map);
    }

    /**
     * 市场行情动态
     * @param pageNum
     * @param pageSize
     * @return map
     */
    @GetMapping("/getQuotationDynamic")
    public R getQuotationDynamic() {
        startPage();
        List<Quotation> list = quotationService.selectQuotationList(new Quotation());
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",list);
        return R.ok(map);
    }

    /**
     * test 数字提示
     * @return
     */
    @GetMapping("/test2")
    public R test2() {
        List<Member> list = memberService.selectMemberList(new Member());
       for (Member M : list) {
           NumberTips tipsByMemberId = numberTipsService.selectNumberTipsByMemberId(M.getId());
           if (tipsByMemberId == null) {
               NumberTips numberTips = new NumberTips();
               numberTips.setMemberId(M.getId());
               numberTipsService.insertNumberTips(numberTips);
           }
       }
        return R.ok();
    }

    /**
     * 留言文字删除
     * @param memberId：用户ID
     * @param infoId：留言信息ID
     * @return
     */
    @GetMapping("/messageTextDeletion")
    public R messageTextDeletion(String memberId, String infoId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        if (infoId == null || infoId.equals("")) {
            return R.error("缺少留言ID");
        }
        MessageInfo messageInfoById = messageInfoService.selectMessageInfoById(infoId);
        if (messageInfoById != null) {
            if (messageInfoById.getMemberId().equals(memberId)) {
                messageInfoById.setMemberStatus(1);
            } else {
                messageInfoById.setMessageMemberStatus(1);
            }
            messageInfoService.updateMessageInfo(messageInfoById);
        }
        return R.ok();
    }

    /**
     * 进入分销中心
     * @param memberId：用户ID
     * @return
     */
    @GetMapping("/distributionCenter")
    public R distributionCenter(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member memberById = memberService.selectMemberById(memberId);
        HashMap<String, Object> map = new HashMap<>();
        if (memberById != null) {
            // 用户返佣金额
            BigDecimal rakeBackByMemberId = coinRecordService.memberRakeBackByMemberId(memberId);
            // 用户提现金额
            BigDecimal cashOutByMemberId = coinRecordService.memberCashOutByMemberId(memberId);
            // 我的余额
            BigDecimal myBalance = rakeBackByMemberId.subtract(cashOutByMemberId);
            map.put("canWithdrawal", myBalance);// 可提现
            map.put("grandTotal", rakeBackByMemberId);// 累计获得
            map.put("qrCode", memberById.getQrCode());// 用户二维码
        }
        return R.ok(map);
    }

    /**
     * 佣金收益列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/commissionRevenuesList")
    public R commissionRevenuesList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                   String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        HaoqiCoinRecord coinRecord = new HaoqiCoinRecord();
        coinRecord.setType(0);
        PageHelper.startPage(pageNum,pageSize);
        List<HaoqiCoinRecordDto> list = coinRecordService.selectHaoqiCoinRecordList(coinRecord);
        HashMap<String, Object> map = new HashMap<>();
        // 用户返佣金额
        BigDecimal rakeBackByMemberId = coinRecordService.memberRakeBackByMemberId(memberId);
        // 共邀请
        Member member = new Member();
        member.setIntroUser(memberId);
        List<Member> memberList = memberService.selectMemberList(member);
        PageInfo<HaoqiCoinRecordDto> pageInfo = new PageInfo<>(list);
        map.put("rakeBackByMemberId",rakeBackByMemberId);// 佣金总数
        map.put("invitationNum",memberList.size());// 共邀请
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 提现记录列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/withdrawalRecordList")
    public R withdrawalRecordList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                    String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        HaoqiCoinRecord coinRecord = new HaoqiCoinRecord();
        coinRecord.setType(1);
        PageHelper.startPage(pageNum,pageSize);
        List<HaoqiCoinRecordDto> list = coinRecordService.selectHaoqiCoinRecordList(coinRecord);
        HashMap<String, Object> map = new HashMap<>();
        PageInfo<HaoqiCoinRecordDto> pageInfo = new PageInfo<>(list);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 分享记录列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param memberId 用户ID
     * @return R.ok();
     */
    @GetMapping("/shareRecordList")
    public R shareRecordList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                  String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        // 分享记录
        Member member = new Member();
        member.setIntroUser(memberId);
        PageHelper.startPage(pageNum,pageSize);
        List<Member> list = memberService.selectMemberList(member);
        PageInfo<Member> pageInfo = new PageInfo<>(list);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 用户提现
     * @param params memberId：用户ID
     *               num：提现金额
     * @return
     */
    @PostMapping("/memberCashOut")
    public R memberCashOut(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("memberId")||StringUtils.isEmpty(params.get("memberId").toString())){
            return R.error("缺少用户ID");
        }
        if (!params.containsKey("num")||StringUtils.isEmpty(params.get("num").toString())){
            return R.error("缺少提现金额");
        }

        String memberId = params.get("memberId").toString();
        // 提现金额
        BigDecimal num = new BigDecimal(params.get("num").toString());
        if (num.compareTo(BigDecimal.ZERO) != 1){
            return R.error("请输入正确金额");
        }
        Member memberById = memberService.selectMemberById(memberId);
        if (memberById == null) {
            return R.error("用户异常，请联系管理员");
        }
        // 用户返佣金额
        BigDecimal rakeBackByMemberId = coinRecordService.memberRakeBackByMemberId(memberId);
        // 用户提现金额
        BigDecimal cashOutByMemberId = coinRecordService.memberCashOutByMemberId(memberId);
        // 我的余额
        BigDecimal myBalance = rakeBackByMemberId.subtract(cashOutByMemberId);
        if (myBalance.compareTo(num) < 0){
            return R.error("余额不足");
        } else {
            HaoqiCoinRecord coinRecord = new HaoqiCoinRecord();
            coinRecord.setMemberId(memberId);
            coinRecord.setNum(num);
            coinRecord.setStatus(0);
            coinRecord.setType(1);
            coinRecordService.insertHaoqiCoinRecord(coinRecord);
        }
        return R.ok();
    }

    /**
     * 获取企业号
     * @param memberId：用户ID
     * @return
     */
    @GetMapping("/getCompanyNum")
    public R getCompanyNum(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Company company = companyService.selectCompanyByMemberId(memberId);
        HashMap<String, Object> map = new HashMap<>();
        if (company != null) {
            map.put("companyNum", company.getCompanyNum());// 企业号
        }
        return R.ok(map);
    }

    /**
     * 获取我的公司简介
     * @param memberId：用户ID
     * @return
     */
    @GetMapping("/getMyCompanyInfo")
    public R getMyCompanyInfo(String memberId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        HashMap<String, Object> map = new HashMap<>();
        CompanyInfo companyInfo = companyInfoService.selectCompanyInfoByCompanyId(memberId);
        map.put("data", companyInfo);// 公司简介
        return R.ok(map);
    }

    /**
     * 编辑名片-展示主营业务
     * @param memberId：用户ID
     * @param industryId：行业ID
     * @return
     */
    @GetMapping("/showBusiness")
    public R showBusiness(String memberId, String industryId) {
        if (memberId == null || memberId.equals("")) {
            return R.error("缺少用户ID");
        }
        Member memberById = memberService.selectMemberById(memberId);
        if (memberById == null) {
            return R.error("用户异常");
        }
        HashMap<String, Object> map = new HashMap<>();
        if (memberById.getIndustry() == null) {
            if (industryId == null) {
                map.put("business", "无");
            } else {
                MemberBusiness memberBusiness = new MemberBusiness();
                memberBusiness.setIndustryId(industryId);
                memberBusiness.setDelFlag(0);
                List<MemberBusiness> businessList = memberBusinessService.selectMemberBusinessList(memberBusiness);
                if (businessList.size() > 0) {
                    map.put("business", businessList.get(0).getBusinessName());
                }
            }
        } else if (industryId != null && !industryId.equals("")) {
            // 主营业务类型：0-展示选择 1-展示编辑
            if (memberById.getBusinessType() == 0) {
                // 本来的行业=搜索的行业 我的主营业务名不为空
                if (memberById.getIndustry().equals(industryId) && memberById.getBusiness() != null) {
                    map.put("business", memberById.getBusiness());
                } else if (!memberById.getIndustry().equals(industryId)) {// 展示行业下的第一个主营业务
                    MemberBusiness memberBusiness = new MemberBusiness();
                    memberBusiness.setIndustryId(industryId);
                    memberBusiness.setDelFlag(0);
                    List<MemberBusiness> businessList = memberBusinessService.selectMemberBusinessList(memberBusiness);
                    if (businessList.size() > 0) {
                        map.put("business", businessList.get(0).getBusinessName());
                    }
                }
            } else {
                map.put("business", memberById.getBusinessName());//展示编辑的主营业务
            }
        } else {
            map.put("business", memberById.getBusinessName());//展示编辑的主营业务
        }
        return R.ok(map);
    }
}
